利用注解+反射消除重复代码,你学会了吗?

28 篇文章 1 订阅
9 篇文章 0 订阅

我们工作一定年限(3-5年),很多同学抱怨,业务开发没有什么技术含量,用不到设计模式,平时写代码都是CRUD,要么就是API调用,平常最多写一个单例模式,其他高级特性和设计模式根本没有用武之地

今天举一个在工作中很常用的例子,假设银行提供了一些 API 接口,对参数的序列化有点特殊,不使用 JSON,而是需要我们把参数依次拼在一起构成一个大字符串

按照银行提供的 API 文档的顺序,把所有参数构成定长的数据,然后拼接在一起作为整个字符串。

因为每一种参数都有固定长度,未达到长度时需要做填充处理

  • 字符串类型的参数不满长度部分需要以下划线右填充,也就是字符串内容靠左;
  • 数字类型的参数不满长度部分以 0 左填充,也就是实际数字靠右;
  • 货币类型的表示需要把金额向下舍入 2 位到分,以分为单位,作为数字类型同样进行左填充。
  • 对所有参数做 MD5 操作作为签名(为了方便理解,Demo 中不涉及加盐处理)

比如,创建用户方法和支付方法的定义是这样的

 

Copy

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(); } }

 

Copy

/** * @author: rfs * @create: 2021/8/20 * @description: 我们定义一个接口 API 的注解 BankAPI,包含接口 URL 地址和接口说明 **/ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Documented @Inherited public @interface BackAPI { String desc() default ""; String url() default ""; }

 

Copy

/** * @author: rfs * @create: 2021/8/20 * @description: 用于描述接口的每一个字段规范,包含参数的次序、类型和长度三个属性 **/ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @Documented @Inherited public @interface BankAPIField { int order()default -1; int length()default -1; BankAPIFieldType type(); }

 

Copy

/** * @author: rfs * @create: 2021/8/20 * @description: 字段类型枚举 **/ public enum BankAPIFieldType { S { @Override public String format(Object value, BankAPIField bankAPIField) { return String.format("%-" + bankAPIField.length() + "s", value.toString()).replace(' ', '_'); } }, N { @Override public String format(Object value, BankAPIField bankAPIField) { return String.format("%" + bankAPIField.length() + "s", value.toString()).replace(' ', '0'); } }, M { @Override public String format(Object value, BankAPIField bankAPIField) { if (!(value instanceof BigDecimal)) { throw new RuntimeException(String.format("{} 的 {} 必须是BigDecimal")); } return String.format(String.format("%0" + bankAPIField.length() + "d", ((BigDecimal) value).setScale(2, RoundingMode.DOWN).multiply(new BigDecimal("100")).longValue())); } }; public abstract String format(Object value, BankAPIField bankAPIField); }

创建一个AbstractAPI 公共抽象类是一个空实现,因为这个案例中的接口并没有公共数据可以抽象放到基类。
接下来两个Http接口继承这个基类,并添加响应的注解

 

Copy

@Data @BackAPI(url = "/bank/pay",desc = "支付接口") public class PayAPI extends AbstractAPI { @BankAPIField(order = 1,type = BankAPIFieldType.N,length = 20) private long userId; @BankAPIField(order = 2,type = BankAPIFieldType.M,length = 10) private BigDecimal amount; } @Data @BackAPI(url = "/bank/createUser",desc = "创建用户接口") public class CreateUserAPI extends AbstractAPI { @BankAPIField(order = 1,type = BankAPIFieldType.S,length = 10) private String name; @BankAPIField(order = 2, type =BankAPIFieldType.S, length = 18) private String identity; @BankAPIField(order = 4, type =BankAPIFieldType.S, length = 11) private String mobile; @BankAPIField(order = 3, type = BankAPIFieldType.N, length = 5) private int age; }

接下来就是利用反射配合注解获取动态的接口参数,所有处理参数排序、填充、加签、请求调用的核心逻辑,都汇聚在了 remoteCall 方法中

 

Copy

public static String remoteCall(AbstractAPI api) { BackAPI backAPI = api.getClass().getAnnotation(BackAPI.class); StringBuilder stringBuilder = new StringBuilder(); Arrays.stream(api.getClass().getDeclaredFields()) .filter(field -> field.isAnnotationPresent(BankAPIField.class)) .sorted(Comparator.comparingInt(a -> a.getAnnotation(BankAPIField.class).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(); } stringBuilder.append(bankAPIField.type().format(value, bankAPIField)); }); //签名逻辑 // 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 ""; }

有了这个核心方法,BankService 中每一个接口的实现就非常简单了,只是参数的组装,然后调用 remoteCall 即可。

 

Copy

/** * @author: rfs * @create: 2021/8/20 * @description: 创建用户接口 **/ public static String createUser(String name, String identity, String mobile, int age) { CreateUserAPI createUserAPI = new CreateUserAPI(); createUserAPI.setName(name); createUserAPI.setIdentity(identity); createUserAPI.setAge(age); createUserAPI.setMobile(mobile); return remoteCall(createUserAPI); } /** * @author: rfs * @create: 2021/8/20 * @description: 支付接口 **/ public static String pay(long userId, BigDecimal amount) { PayAPI payAPI = new PayAPI(); payAPI.setUserId(userId); payAPI.setAmount(amount); return remoteCall(payAPI); }

许多涉及类结构性的通用处理,都可以按照这个模式来减少重复代码!!

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您解答关于Java自定义字典类、自定义注解反射注入字典值到实体类的问题。 首先,自定义字典类是一种将一些常量或者枚举类型的值封装在一起的方式。可以让代码更加易读、易维护。比如,我们可以定义一个字典类,用来存储一些常量值,如: ``` public class GenderDict { public static final Integer MALE = 1; public static final Integer FEMALE = 2; } ``` 接下来,我们可以使用自定义注解来标记需要注入字典值的实体类的属性上。比如,我们可以定义一个注解类,如: ``` @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Dictionary { String value(); } ``` 在该注解类中,我们使用@Retention和@Target注解来指定注解的保留策略和作用范围。同时,我们还可以使用value属性来指定注解的值,即该属性需要注入的字典值的名称。 最后,我们可以使用反射机制,在运行时动态地将字典值注入到实体类中。具体的实现方式如下: ``` public class DictionaryInjector { public static void injectDictionary(Object obj) throws IllegalAccessException { Class<?> clazz = obj.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(Dictionary.class)) { Dictionary dict = field.getAnnotation(Dictionary.class); String dictName = dict.value(); String dictValue = getDictValue(dictName); field.setAccessible(true); field.set(obj, dictValue); } } } private static String getDictValue(String dictName) { // 从字典类中获取对应的字典值 // 这里可以使用反射或者其他方式来实现 return GenderDict.MALE.equals(dictName) ? "男" : "女"; } } ``` 在上述代码中,我们首先使用Class对象获取实体类的所有属性,然后通过判断该属性是否被@Dictionary注解标记来确定是否需要注入字典值。如果需要注入,则从注解中获取字典值的名称,然后通过反射机制将字典值注入到实体类的属性中。 最后,我们可以在代码中使用如下方式来注入字典值: ``` public class User { @Dictionary("gender") private String gender; // getters and setters } public class Main { public static void main(String[] args) throws IllegalAccessException { User user = new User(); DictionaryInjector.injectDictionary(user); System.out.println(user.getGender()); // 输出 "男" } } ``` 在上述代码中,我们首先定义了一个User类,并在其中使用@Dictionary注解标记了gender属性。然后,在Main类中,我们创建了一个User对象,并调用DictionaryInjector类的injectDictionary方法来注入字典值。最后,我们通过调用User对象的getGender方法来获取注入后的字典值。 希望这能够帮助您解决问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值