为了简写这行代码,我竟使用静态和动态编译技术

打印 上一主题 下一主题

主题 887|帖子 887|积分 2661

背景

在我们系统中有这么一个需求,业务方会通过mq将一些用户信息传给我们,我们的服务处理完后,再将信息转发给子系统。mq的内容如下:
  1. @Data
  2. public class Person {
  3.    
  4.     //第一部分
  5.     private Integer countryId;   
  6.     private Integer companyId;
  7.     private String uid;
  8.     //第二部分
  9.     private User userBaseInfo;
  10.     private List<UserContact> contactList;
  11.     private List<UserAddress> addressList;
  12.     private UserEducation educationInfo;
  13.     private UserProfession professionInfo;
  14.     private List<Order> orderList;
  15.     private List<Bill> billList;
  16.     private List<UserMerchant> merchantList;
  17.     private List<UserOperate> operateList;
  18.     private BeneficialOwner beneficialOwnerInfo;
  19. }   
复制代码
主要分为两部分,第一部分是用户id,这部分用于唯一标识一个用户,不会改变。第二部分是一些基础信息,账单、订单、联系方式、地址等等,这部分信息内容经常增加。
后面业务新增了一个逻辑,会对第二部某些信息进行剔除,最后这部分信息如果还有,才转发到子系统。所以开发同学新增这么一个很长的条件判断:
  1. public static boolean isNull(BizData bizData) {
  2.     return CollectionUtils.isEmpty(bizData.getBillList()) && CollectionUtils.isEmpty(bizData.getOrderList()) && CollectionUtils.isEmpty(bizData.getAddressList()) && CollectionUtils.isEmpty(bizData.getContactList()) && bizData.getEducationInfo() == null && bizData.getProfessionInfo() == null && bizData.getUserBaseInfo() == null && CollectionUtils.isEmpty(bizData.getMerchantList()) && CollectionUtils.isEmpty(bizData.getOperateList()) && bizData.getBeneficialOwnerInfo() == null;
  3. }
复制代码
在review代码的时候,发现这里是一个“坑”,是一个会变化的点,以后新增信息,很可能会漏了来改这里,在我的开发过程中,最担心的就是遇到这些会变化点又写死逻辑的,过段时间我就会忘记,如果换个人接手,那更难以发现,容易出现bug。因为这个条件判断并不会自动随着我们新增字段而自动修改,完全靠人记忆,容易遗漏。
思考

那有没有办法做到新增信息不需要修改这里吗,也就是isNull方法可以自动动态判断属性是否为空呢?
首先我们都会想到反射,通过反射可以读取class所有字段,每次处理都反射判断一下字段值是否为空即可做到动态判断。但反射的性能太低了,对于我们来说这是个调用量非常大的方法,尽量做到不损失性能,所以反射不在本次考虑范围内。
既然有不变和变化的两部分,那么我们可以先将其分离,将不变的抽取到一个基类去。为了简化代码,第二部分我们只保留两个属性。
  1. @Data
  2. public class PersonBase {
  3.    
  4.     //第一部分
  5.     private Integer countryId;   
  6.     private Integer companyId;
  7.     private String uid;
  8. }
  9. @Data
  10. public class Person extend PersonBase {
  11.    
  12.     //第二部分...
  13.     private User userBaseInfo;
  14.     private List<UserContact> contactList;
  15. }
复制代码
要动态生成isNull方法,可以先从结果反推是怎么样的。可以有如下两种方式:
1、在原Person类新增一个isNull方法,这种方式的特点是我们可以直接通过对象直接调用方法,如:
  1. @Data
  2. public class Person extend PersonBase {
  3.         
  4.     private User userBaseInfo;
  5.     private List<UserContact> contactList;
  6.     public boolean isNull() {
  7.         return this.userBaseInfo != null && this.contactList != null;
  8.     }
  9. }
复制代码
2、动态新增一个类,动态新增一个isNull方法,参数是BizData。这种方式无法通过Preson对象调用方法,甚至无法直接通过生成类调用方法,因为动态类的名称我们都无法预知。如:
  1. public class Person$Generated {
  2.    
  3.     public boolean isNull(BizData bizData) {
  4.         return bizData.getUserBaseInfo() != null && bizData.getContactList() != null;
  5.     }
  6. }
复制代码
这就是我们本篇要解决的问题,通过静态/动态编译技术生成代码。这里静态是指“编译期”,也就是类和方法在编译期间就存在了,动态是指“运行时”,意思编译期间类还不存在,等程序运行时才被加载,链接,初始化。
这两种方式大家实际都经常接触到,lombok可以帮我们生成getter/setter,本质就是在编译期为类新增方法,spring无处不在的动态代理就是运行时生成的类。
动态编译

我们先来看动态编译,因为动态编译我们都比较熟,也比较简单,在spring中随处可见,例如我们熟悉的动态代理类就是动态生成的。
我们编写的java代码会先经过编译称为字节码,字节码再由jvm加载运行,所以动态生成类就是要编写相应的字节码。
但由于java字节码太复杂了,需要熟悉各种字节码指令,一般我们不会直接编写字节码代码,会借助字节码框架或工具来生成。例如查看简单的hello world类的字节码,idea -> view -> show bytecode。
  1. public class HelloWorld {
  2.         public static void main(String[] args) {
  3.                 System.out.println("hello world");
  4.         }
  5. }
复制代码

ASM 介绍

ASM是一个通用的 Java 字节码操作和分析框架。它可用于直接以二进制形式修改现有类或动态生成类。ASM 提供了一些常见的字节码转换和分析算法,可以从中构建自定义的复杂转换和代码分析工具。ASM 提供与其他 Java 字节码框架类似的功能,但重点关注性能。因为它的设计和实现尽可能小且尽可能快,所以它非常适合在动态系统中使用(但当然也可以以静态方式使用,例如在编译器中)。
接下来我们用asm来生成hello world,如下:
  1. public class HelloWorldGenerator {
  2.     public static void main(String[] args) throws Exception {
  3.         // 创建一个ClassWriter,用于生成字节码
  4.         ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
  5.         
  6.         // 定义类的头部信息
  7.         cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "HelloWorld", null, "java/lang/Object", null);
  8.         // 生成默认构造函数
  9.         MethodVisitor constructor = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
  10.         constructor.visitCode();
  11.         constructor.visitVarInsn(Opcodes.ALOAD, 0);
  12.         constructor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
  13.         constructor.visitInsn(Opcodes.RETURN);
  14.         constructor.visitMaxs(1, 1);
  15.         constructor.visitEnd();
  16.         // 生成main方法
  17.         MethodVisitor mainMethod = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
  18.         mainMethod.visitCode();
  19.         // 打印"Hello, World!"到控制台
  20.         mainMethod.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
  21.         mainMethod.visitLdcInsn("Hello, World!");
  22.         mainMethod.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);
  23.         mainMethod.visitInsn(Opcodes.RETURN);
  24.         mainMethod.visitMaxs(2, 2);
  25.         mainMethod.visitEnd();
  26.         // 完成类的生成
  27.         cw.visitEnd();
  28.         // 将生成的字节码写入一个类文件
  29.         byte[] code = cw.toByteArray();
  30.         MyClassLoader classLoader = new MyClassLoader();
  31.         Class<?> helloWorldClass = classLoader.defineClass("HelloWorld", code);
  32.         
  33.         // 创建一个实例并运行main方法
  34.         helloWorldClass.getDeclaredMethod("main", String[].class).invoke(null, (Object) new String[0]);
  35.     }
  36.     // 自定义ClassLoader用于加载生成的类
  37.     private static class MyClassLoader extends ClassLoader {
  38.         public Class<?> defineClass(String name, byte[] b) {
  39.             return defineClass(name, b, 0, b.length);
  40.         }
  41.     }
  42. }
复制代码
上面的代码我是用chatgpt生成的,只需要输入:“帮我用java asm字节码框架生成一个hello world,并注释每行代码写明它的作用。”
相比直接编写字节码指令,asm将其封装成各种类和方法,方便我们理解和编写,实际上asm还是比较底层的框架,所以许多框架会再它的基础上继续封装,如cglib,byte buddy等。
可以看到生成的结果和我们自己编写的是一样的。

实现

接下来我们就用asm来动态生成上面的isNull方法,由于目标类是动态生成的,类名我们都不知道,但我们最终是要调用它的isNull方法,这怎么办呢?
我们可以定义一个接口,然后动态生成的类实现它,最终通过接口来调用它,这就是接口的好处之一,我们可以不关注具体类是谁,内部怎么实现。
如定义接口如下:
  1. public interface NullChecker<T> {
  2.         /**
  3.          * 参数固定为origin
  4.          *
  5.          * @param origin 名称必须为origin
  6.          */
  7.         Boolean isNull(T origin);
  8. }
复制代码
这是个泛型接口,也就是所有类型都可以这么用。isNull方法参数名称必须为origin,因为在生成字节码时写死了这个名称。
接下来编写核心的生成方法,如下:
  1. public class ClassByteGenerator implements Opcodes {
  2.         public static byte[] generate(Class originClass) {
  3.                 ClassWriter classWriter = new ClassWriter(0);
  4.                 MethodVisitor methodVisitor;
  5.                 //将.路径替换为/
  6.                 String originClassPath = originClass.getPackage().getName().replace(".", "/") + "/" + originClass.getSimpleName();
  7.                 //动态生成类的名称:原类$ASMGenerated
  8.                 String generateClassName = originClass.getSimpleName() + "$ASMGenerated";
  9.                 String generateClassPatch = ClassByteGenerator.class.getPackage().getName().replace(".", "/") + "/" + generateClassName;
  10.                 String nullCheckerClassPath = NullChecker.class.getPackage().getName().replace(".", "/") + "/" + NullChecker.class.getSimpleName();
  11.                 classWriter.visit(V1_8, ACC_PUBLIC | ACC_SUPER, generateClassPatch, null, "java/lang/Object", new String[]{nullCheckerClassPath});
  12.                 classWriter.visitSource(generateClassName + ".java", null);
  13.                 {
  14.                         methodVisitor = classWriter.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
  15.                         methodVisitor.visitCode();
  16.                         Label label0 = new Label();
  17.                         methodVisitor.visitLabel(label0);
  18.                         methodVisitor.visitLineNumber(7, label0);
  19.                         methodVisitor.visitVarInsn(ALOAD, 0);
  20.                         methodVisitor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
  21.                         methodVisitor.visitInsn(RETURN);
  22.                         Label label1 = new Label();
  23.                         methodVisitor.visitLabel(label1);
  24.                         methodVisitor.visitLocalVariable("this", "L" + generateClassPatch + ";", null, label0, label1, 0);
  25.                         methodVisitor.visitMaxs(1, 1);
  26.                         methodVisitor.visitEnd();
  27.                 }
  28.                 {
  29.                         methodVisitor = classWriter.visitMethod(ACC_PUBLIC, "isNull", "(L" + originClassPath + ";)Ljava/lang/Boolean;", null, null);
  30.                         methodVisitor.visitParameter("origin", 0);
  31.                         methodVisitor.visitCode();
  32.                         Label label0 = new Label();
  33.                         methodVisitor.visitLabel(label0);
  34.                         methodVisitor.visitVarInsn(ALOAD, 1);
  35.                         Label label1 = new Label();
  36.                         int index = 0;
  37.                         //过滤掉基类的
  38.                         PropertyDescriptor[] propertyDescriptors = Arrays.stream(BeanUtils.getPropertyDescriptors(originClass))
  39.                                         .filter(p -> p.getReadMethod().getDeclaringClass() == originClass)
  40.                                         .toArray(PropertyDescriptor[]::new);
  41.                         for (PropertyDescriptor pd : propertyDescriptors) {
  42.                                 String descriptor = "()" + Type.getDescriptor(pd.getPropertyType());
  43.                                 if (index == 0) {
  44.                                         methodVisitor.visitMethodInsn(INVOKEVIRTUAL, originClassPath, pd.getReadMethod().getName(), descriptor, false);
  45.                                 } else if (index > 0 && index < propertyDescriptors.length - 1) {
  46.                                         methodVisitor.visitJumpInsn(IFNULL, label1);
  47.                                         methodVisitor.visitVarInsn(ALOAD, 1);
  48.                                         methodVisitor.visitMethodInsn(INVOKEVIRTUAL, originClassPath, pd.getReadMethod().getName(), descriptor, false);
  49.                                 } else {
  50.                                         methodVisitor.visitJumpInsn(IFNULL, label1);
  51.                                         methodVisitor.visitVarInsn(ALOAD, 1);
  52.                                         methodVisitor.visitMethodInsn(INVOKEVIRTUAL, originClassPath, pd.getReadMethod().getName(), descriptor, false);
  53.                                         methodVisitor.visitJumpInsn(IFNULL, label1);
  54.                                         methodVisitor.visitInsn(ICONST_1);
  55.                                 }
  56.                                 index++;
  57.                         }
  58.                         Label label2 = new Label();
  59.                         methodVisitor.visitJumpInsn(GOTO, label2);
  60.                         methodVisitor.visitLabel(label1);
  61.                         methodVisitor.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
  62.                         methodVisitor.visitInsn(ICONST_0);
  63.                         methodVisitor.visitLabel(label2);
  64.                         methodVisitor.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[]{Opcodes.INTEGER});
  65.                         methodVisitor.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false);
  66.                         methodVisitor.visitInsn(ARETURN);
  67.                         Label label3 = new Label();
  68.                         methodVisitor.visitLabel(label3);
  69.                         methodVisitor.visitLocalVariable("this", "L" + generateClassPatch + ";", null, label0, label3, 0);
  70.                         methodVisitor.visitLocalVariable("origin", "L" + originClassPath + ";", null, label0, label3, 1);
  71.                         methodVisitor.visitMaxs(1, 2);
  72.                         methodVisitor.visitEnd();
  73.                 }
  74.                 {
  75.                         methodVisitor = classWriter.visitMethod(ACC_PUBLIC | ACC_BRIDGE | ACC_SYNTHETIC, "isNull", "(Ljava/lang/Object;)Ljava/lang/Boolean;", null, null);
  76.                         methodVisitor.visitParameter("origin", ACC_SYNTHETIC);
  77.                         methodVisitor.visitCode();
  78.                         Label label0 = new Label();
  79.                         methodVisitor.visitLabel(label0);
  80.                         methodVisitor.visitLineNumber(7, label0);
  81.                         methodVisitor.visitVarInsn(ALOAD, 0);
  82.                         methodVisitor.visitVarInsn(ALOAD, 1);
  83.                         methodVisitor.visitTypeInsn(CHECKCAST, originClassPath);
  84.                         methodVisitor.visitMethodInsn(INVOKEVIRTUAL, generateClassPatch, "isNull", "(L" + originClassPath + ";)Ljava/lang/Boolean;", false);
  85.                         methodVisitor.visitInsn(ARETURN);
  86.                         Label label1 = new Label();
  87.                         methodVisitor.visitLabel(label1);
  88.                         methodVisitor.visitLocalVariable("this", "L" + generateClassPatch + ";", null, label0, label1, 0);
  89.                         methodVisitor.visitMaxs(2, 2);
  90.                         methodVisitor.visitEnd();
  91.                 }
  92.                 classWriter.visitEnd();
  93.                 return classWriter.toByteArray();
  94.         }
  95. }
复制代码
代码有点长,可能你会想还是用chatgpt生成,但这种逻辑性比较强的它就无能为力了。不过我们还有工具可以生成它,我使用的是ASM Bytecode Viewer,idea中安装插件即可。
首先将要实现的结果用代码写出来,然后右键使用ASM Bytecode Viewer,就可以看到对应的asm代码。当然实际我们是要遍历类的所有字段,就是for循环遍历属性的那一部分,这需要自己写,也不难,在插件生成代码后稍微调整下即可。
  1. public class MyPersonGenerated implements NullChecker<Person> {
  2.         @Override
  3.         public Boolean isNull(Person person) {
  4.                 return person.getUserBaseInfo() != null && person.getContactList() != null;
  5.         }
  6. }
复制代码

八股文背多了就知道类生命周期是:加载 -> 链接(验证,准备,解析) -> 初始化 -> 使用 -> 卸载。所以首先要使用ClassLoader将动态类加载到jvm,我们可以定义一个类继承抽象类ClassLoader,调用它的defineClass。
  1. public class MyClassLoader extends ClassLoader {
  2.         public Class<?> defineClass(byte[] b) {
  3.                 return super.defineClass(null, b, 0, b.length);
  4.         }
  5. }
复制代码
使用如下,当然实际情况中我们会将生成的NullChecker赋值给一个全局变量缓存,不用每次都newInstance创建。
  1. MyClassLoader myClassLoader = new MyClassLoader();
  2. byte[] bytes = ClassByteGenerator.generate(Person.class);
  3. Class<?> personNullCheckerCls = myClassLoader.defineClass(bytes);
  4. NullChecker personNullChecker = (NullChecker) personNullCheckerCls.newInstance();
  5. boolean result = o.isNull(person);
复制代码
也可以将生成类的字节保存到文件,然后拖到idea观察结果,如下:
  1. try (FileOutputStream fos = new FileOutputStream("./Person$ASMGenerated.class")) {
  2.         fos.write(bytes); // 将字节数组写入.class文件
  3. } catch (IOException e) {
  4.         throw e;
  5. }
复制代码

静态编译

看完动态编译我们再看静态编译。java代码编译和执行的整个过程包含三个主要机制:1.java源码编译机制 2.类加载机制 3.类执行机制。其中java源码编译由3个过程组成:1.分析和输入到符号表 2.注解处理 3.语义分析和生成class文件。如下:

在介绍mapstruct这篇时我们也有提到,其中主要就是在源码编译的注解处理阶段,可以插入我们的自定义代码。
例如我们新建工程,定义如下注解,它标识的类就会对应生成一个含isNull方法的类。其中RetentionPolicy.SOURCE表示在源码阶段生效,在运行时是读不到这个注解的,lombok的注解也是这个道理。
  1. @Retention(RetentionPolicy.SOURCE)
  2. @Target(ElementType.TYPE)
  3. public @interface GenerateIsNullMethod {
  4.         String value() default "";
  5. }
复制代码
接着编写注解处理器,在发现GenerateIsNullMethod注解时,进入处理逻辑。
[code]@SupportedAnnotationTypes("com.example.mapstruct.processor.GenerateIsNullMethod")@SupportedSourceVersion(SourceVersion.RELEASE_8)@AutoService(Processor.class)public class IsNullAnnotationProcessor extends AbstractProcessor {        private ProcessingEnvironment processingEnv;        @Override        public synchronized void init(ProcessingEnvironment processingEnv) {                super.init(processingEnv);                this.processingEnv = processingEnv;        }        @Override        public boolean process(Set

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

兜兜零元

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表