文章目录
- 自定义注解
- 类定义
- 反射和注解取值格式化参数
- 测试
自定义注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PropertyAnnotation {
//字段类型: STRING->0,Number 1,Decimal 2,DateTime 3, Date 4 ,int 5,Float 6,Double 7
int type() default 0;
//时间格式
String dateformat() default "yyyy-MM-dd";
//最大长度默认50
int maxlen() default 50;
//是否强制截取
boolean truncate() default false;
//填充符号 固定长度不满足长度填充字符,金额字段一般是0,一般是左填充
String fillpadding() default "*";
//默认值
String value() default "";
}
类定义
/**
* 支付的参数
*/
public class PayParamInfo {
//支付标题
@PropertyAnnotation(type = 0,maxlen = 20,truncate = true,value = "支付订单",fillpadding = "#")
private String payTitle;
//支付日期时间
@PropertyAnnotation(type =3,maxlen = 14,dateformat = "yyyy-MM-dd hh24:mi:ss")
private LocalDateTime payDateTime;
//支付数量
@PropertyAnnotation(type = 5,maxlen = 8,fillpadding = "0")
private int payNum;
//支付金额 分
@PropertyAnnotation(type = 2,maxlen = 18,fillpadding = "0")
private BigDecimal payAmount;
///省略set get
}
反射和注解取值格式化参数
/**
* 格式化参数
* @param payParamInfo
* @return
* @throws IllegalAccessException
*/
public String FormatParams(PayParamInfo payParamInfo) throws IllegalAccessException {
StringBuilder sb = new StringBuilder();
for (Field field : payParamInfo.getClass().getDeclaredFields()) {
//获取字段对应的注解
PropertyAnnotation p = field.getDeclaredAnnotation(PropertyAnnotation.class);
if (p != null) {
// 获取Field的值:
Object value = field.get(payParamInfo);
// 数字类型
if (value instanceof BigDecimal) {
String s = value.toString();
if (s.contains(".")) {
s = s.replace(".", "");
}
int Length = p.maxlen();
String format = StringUtils.leftPad(s, Length, p.fillpadding());
sb.append(format);
}else if (value instanceof LocalDateTime){
//日期时间格式
String format = LocalDateTimeUtil.format((LocalDateTime) value, DatePattern.NORM_DATETIME_PATTERN);
//format.replaceAll("-", "").replaceAll(" ","").replaceAll(":","");
format = StringUtils.replace(format, "-", "");
format = StringUtils.replace(format, " ", "");
format = StringUtils.replace(format, ":", "");
sb.append(format);
}else{
String format = StringUtils.leftPad(value.toString(), p.maxlen(), p.fillpadding());
sb.append(format);
}
}
}
return sb.toString();
}
测试
public class TestMain {
public static void main(String[] args) throws IllegalAccessException {
PayParamInfo payParamInfo=new PayParamInfo();
payParamInfo.setPayAmount(new BigDecimal("10.01"));
payParamInfo.setPayNum(1);
payParamInfo.setPayDateTime(LocalDateTime.now());
payParamInfo.setPayTitle("测试订单");
//格式化参数
System.out.println("拼接的参数:"+payParamInfo.FormatParams(payParamInfo));
}
}
具体详情参见视频!
【Java】自定义注解与反射优雅实现参数拼接
如果有帮助点点关注!