工具类
/**
* 按照字段顺序进行拼接
*
* @param obj 对象,需要在字段上添加FieldOrder注解
* @param fix 拼接符号
* @param <T>
* @return
* @author JeWang
*/
public static <T> String toSpit(T obj, String fix) throws IllegalAccessException {
String ret = "";
Field[] declaredFields = obj.getClass().getDeclaredFields();
Field[] fields = new Field[declaredFields.length];
for (Field declaredField : declaredFields) {
FieldOrder annotation = declaredField.getAnnotation(FieldOrder.class);
int order = annotation.order();
fields[order - 1] = declaredField;
}
for (Field field : fields) {
field.setAccessible(true);
Object o = field.get(obj);
if (o == null) {
ret = ret + "" + fix;
} else {
ret = ret + o + fix;
}
}
return ret;
注解
package cn.daenx.japi.bank.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldOrder {
/**
* 标注该属性的顺序
* 从1开始,不可跳跃
*
* @return 该属性的顺序
*/
int order();
}
示例实体类
package cn.daenx.japi.bank.vo.req;
import cn.daenx.japi.bank.annotation.FieldOrder;
import lombok.Data;
@Data
public class R0804ReqVo {
/**
* 交易代码
*/
@FieldOrder(order = 1)
private String tradeCode;
/**
* POS厂商代码
*/
@FieldOrder(order = 2)
private String posFirmCode;
/**
* POS唯一编号
*/
@FieldOrder(order = 3)
private String posOnlyCode;
/**
* 银行卡账户名称
*/
@FieldOrder(order = 4)
private String bankAccountName;
/**
* 银行卡账户账号
*/
@FieldOrder(order = 5)
private String bankAccountNumber;
/**
* 银行卡发卡行
*/
@FieldOrder(order = 6)
private String bankIssuer;
/**
* 发起方
*/
@FieldOrder(order = 7)
private String fromType;
}
使用方法
//生成请求内容
String reqStr;
try {
reqStr = CommonUtils.toSpit(vo, "|");
} catch (IllegalAccessException e) {
return new R0801ResVo("请求数据转换失败");
}
标签:实体类,java,自定义,FieldOrder,private,annotation,import,order,String
From: https://www.cnblogs.com/daen/p/17123140.html