1. 案例分析
1.1 案例場景
假設銀行提供了一些 API 接口,對參數的序列化有點特殊,不使用 JSON,而是須要咱們把參數依次拼在一塊兒構成一個大字符串php
按照銀行提供的API文檔順序,將全部的參數構成定長的數據,而且拼接在一塊兒做爲一整個字符串面試
由於每一種參數都有固定長度,未達到長度須要進行填充處理api
字符串類型參數不滿長度部分要如下劃線右填充,即字符串內容靠左數組
數字類型的參數不滿長度部分以0左填充,即實際數字靠右微信
貨幣類型的表示須要把金額向下舍入2位到分,以分爲單位,做爲數字類型一樣進行左填充app
參數作MD5 操做做爲簽名ide
1.2 初步代碼實現
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(); } }
這樣作可以基本知足需求,可是存在一些問題:優化
處理邏輯互相之間有重複,稍有不慎就會出現Bugui
處理流程中字符串拼接、加簽和發請求的邏輯,在全部方法重複編碼
實際方法的入參的參數類型和順序,不必定和接口要求一致,容易出錯
代碼層面參數硬編碼,沒法清晰進行覈對
1.3 使用接口和反射優化代碼
1.3.1 實現定義了全部接口參數的POJO類
@Data public class CreateUserAPI { private String name; private String identity; private String mobile; private int age; }
1.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 ""; }
1.3.3 反射配合註解實現動態的接口參數組裝
private static String remoteCall(AbstractAPI api) throws IOException { //從BankAPI註解獲取請求地址 BankAPI bankAPI = api.getClass().getAnnotation(BankAPI.class); bankAPI.url(); StringBuilder stringBuilder = new StringBuilder(); Arrays.stream(api.getClass().getDeclaredFields()) //得到全部字段 .filter(field -> field.isAnnotationPresent(BankAPIField.class)) //查找標記了註解的字段 .sorted(Comparator.comparingInt(a -> a.getAnnotation(BankAPIField.class).order())) //根據註解中的order對字段排序 .peek(field -> field.setAccessible(true)) //設置能夠訪問私有字段 .forEach(field -> { //得到註解 BankAPIField bankAPIField = field.getAnnotation(BankAPIField.class); Object value = ""; try { //反射獲取字段值 value = field.get(api); } catch (IllegalAccessException e) { e.printStackTrace(); } //根據字段類型以正確的填充方式格式化字符串 switch (bankAPIField.type()) { case "S": { stringBuilder.append(String.format("%-" + bankAPIField.length() + "s", value.toString()).replace(' ', '_')); break; } case "N": { stringBuilder.append(String.format("%" + bankAPIField.length() + "s", value.toString()).replace(' ', '0')); break; } case "M": { if (!(value instanceof BigDecimal)) throw new RuntimeException(String.format("{} 的 {} 必須是BigDecimal", api, field)); stringBuilder.append(String.format("%0" + bankAPIField.length() + "d", ((BigDecimal) value).setScale(2, RoundingMode.DOWN).multiply(new BigDecimal("100")).longValue())); break; } default: break; } }); //簽名邏輯 stringBuilder.append(DigestUtils.md2Hex(stringBuilder.toString())); String param = stringBuilder.toString(); long begin = System.currentTimeMillis(); //發請求 String result = Request.Post("http://localhost:45678/reflection" + bankAPI.url()) .bodyString(param, ContentType.APPLICATION_JSON) .execute().returnContent().asString(); log.info("調用銀行API {} url:{} 參數:{} 耗時:{}ms", bankAPI.desc(), bankAPI.url(), param, System.currentTimeMillis() - begin); return result; }
經過反射來動態得到class的信息,並在runtime的時候完成組裝過程。這樣作的好處是開發的時候會方便直觀不少,而後將邏輯與細節隱藏起來,而且集中放到了一個方法當中,減小了重複,以及維護當中bug的出現。
1.3.4 在代碼中的應用
@BankAPI(url = "/bank/createUser", desc = "建立用戶接口") @Data public class CreateUserAPI extends AbstractAPI { @BankAPIField(order = 1, type = "S", length = 10) private String name; @BankAPIField(order = 2, type = "S", length = 18) private String identity; @BankAPIField(order = 4, type = "S", length = 11) //注意這裏的order須要按照API表格中的順序 private String mobile; @BankAPIField(order = 3, type = "N", length = 5) private int age; } @BankAPI(url = "/bank/pay", desc = "支付接口") @Data public class PayAPI extends AbstractAPI { @BankAPIField(order = 1, type = "N", length = 20) private long userId; @BankAPIField(order = 2, type = "M", length = 10) private BigDecimal amount; }
END 來源:https://llchen60.com/利用註解-反射消除重複代碼/ 更多精彩推薦 ☞ Google 鼓勵的 13 條代碼審查標準,建議收藏! ☞ 這些SQL錯誤用法,若是常常犯,說明你的水平還很low...☞ 爲啥不能用uuid作MySQL的主鍵?☞ 微信第 1 行代碼曝光!☞ 奇葩公司按代碼行數算工資,員工一個月提成2.6萬遭開除 最後,推薦給你們一個有趣有料的公衆號:寫代碼的渣渣鵬,回覆 面試 或 資源 送一你整套開發筆記,按期送書有驚喜哦