1. 程式人生 > 其它 >利用註解 + 反射消除重複程式碼

利用註解 + 反射消除重複程式碼

1. 案例場景

初步程式碼實現

public class BankService {

    //建立使用者方法
    public static String createUser(String name, String identity, String mobile, int age) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        //字串靠左,多餘的地方填充_
        stringBuilder.append(String.format("%-10s", name).replace(' ', '_'));
        
//字串靠左,多餘的地方填充_ stringBuilder.append(String.format("%-18s", identity).replace(' ', '_')); //數字靠右,多餘的地方用0填充 stringBuilder.append(String.format("%05d", age)); //字串靠左,多餘的地方用_填充 stringBuilder.append(String.format("%-11s", mobile).replace(' ', '_')); //最後加上MD5作為簽名 stringBuilder.append(DigestUtils.md2Hex(stringBuilder.toString()));
return Request.Post("http://localhost:45678/reflection/bank/createUser") .bodyString(stringBuilder.toString(), ContentType.APPLICATION_JSON) .execute().returnContent().asString(); } //支付方法 public static String pay(long userId, BigDecimal amount) throws IOException { StringBuilder stringBuilder
= new StringBuilder(); //數字靠右,多餘的地方用0填充 stringBuilder.append(String.format("%020d", userId)); //金額向下舍入2位到分,以分為單位,作為數字靠右,多餘的地方用0填充 stringBuilder.append(String.format("%010d", amount.setScale(2, RoundingMode.DOWN).multiply(new BigDecimal("100")).longValue())); //最後加上MD5作為簽名 stringBuilder.append(DigestUtils.md2Hex(stringBuilder.toString())); return Request.Post("http://localhost:45678/reflection/bank/pay") .bodyString(stringBuilder.toString(), ContentType.APPLICATION_JSON) .execute().returnContent().asString(); } }

3. 使用介面和反射優化程式碼

@Data
public class CreateUserAPI {
    private String name;
    private String identity;
    private String mobile;
    private int age;
}

3.2 定義註解本身

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Inherited
public @interface BankAPI {
    String desc() default "";
    String url() default "";
}


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
@Inherited
public @interface BankAPIField {
    int order() default -1;
    int length() default -1;
    String type() default "";
}

https://mp.weixin.qq.com/s/e5pwUduPU6a-yGC9ei0hdQ

故鄉明