最近對(duì)接三方門票系統(tǒng)妆棒,發(fā)現(xiàn)報(bào)文中數(shù)字簽名的生成規(guī)則穗慕,是其他部分的參數(shù)值按照指定的順序拼接在一起經(jīng)過(guò)3Des加密之后經(jīng)過(guò)Md5生成的放典。想著要對(duì)接5-6個(gè)接口辽幌,每個(gè)接口都要按照這種規(guī)則的話忠蝗,會(huì)重復(fù)很多生成簽名的硬編碼现横,此刻想到了Java的反射。
import lombok.Data;
import java.util.List;
/**
* @author jack
*/
@Data
public class CreateOrderReq {
@BeanFieldAnnotation(order = 1)
private String orderNo;
@BeanFieldAnnotation(order = 2)
private String productCode;
private String productName;
@BeanFieldAnnotation(order = 3)
private Integer num;
@BeanFieldAnnotation(order = 4)
private String travelDate;
@BeanFieldAnnotation(order = 5)
private String linkMan;
@BeanFieldAnnotation(order = 6)
private String phone;
@BeanFieldAnnotation(order = 7)
private String certNo;
private List<Tourist> tourists;
@Data
public static class Tourist{
private String name;
private String phone;
private String certNo;
}
}
編寫注解類
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author jack
*/
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface BeanFieldAnnotation {
int order();
}
編寫測(cè)試用例:
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Test {
public static void main(String[] args) {
CreateOrderReq req = new CreateOrderReq();
req.setOrderNo("202403162140180001");
req.setProductCode("3000065");
req.setProductName("成人票");
req.setTravelDate("2024-03-20");
req.setNum(1);
req.setLinkMan("張三");
req.setPhone("18307202406");
req.setCertNo("420621199310062934");
List<CreateOrderReq.Tourist> tourists = Lists.newArrayList();
CreateOrderReq.Tourist tourist = new CreateOrderReq.Tourist();
tourist.setName("張三");
tourist.setPhone("18307202406");
tourists.add(tourist);
req.setTourists(tourists);
List<String> strs = Lists.newArrayList();
Field[] fields = req.getClass().getDeclaredFields();
List<Field> result = getOrderedField(fields);
result.forEach(field -> {
field.setAccessible(true);
try {
strs.add(String.valueOf(field.get(req)) );
} catch (IllegalAccessException e) {
e.printStackTrace();
}
});
System.out.println("拼接后的字符串:"+ Joiner.on("").join(strs));
}
private static List<Field> getOrderedField(Field[] fields){
// 用來(lái)存放所有的屬性域
List<Field> fieldList = new ArrayList<>();
// 過(guò)濾帶有注解的Field
for(Field f:fields){
if(f.getAnnotation(BeanFieldAnnotation.class)!=null){
fieldList.add(f);
}
}
// 這個(gè)比較排序的語(yǔ)法依賴于java 1.8
fieldList.sort(Comparator.comparingInt(
m -> m.getAnnotation(BeanFieldAnnotation.class).order()));
return fieldList;
}
}