javajava-bytecode-asmbytecode-manipulation

Accessing the generated code with bytecode manipulation


I'm currently working on a Java library and I want to add some public static final String fields using bytecode manipulation which just hold some info about an entity. e.g.Customer.TABLE_NAME. I want to be able to access these fields before compile time while writing code something like what lombok allows you to do. Obviously those lombok generated methods don't actually exist before the code has been compiled but we can still see and use them without any problem. How can I achieve something like this?


Solution

  • Have you looked into AspectJ inter-type declarations (ITD)? They do exactly what you need. Of course, you can also use more low-level tools like Byte Buddy and Javassist or really low level ones like ASM in order to achieve the same.

    Most of those tools can be used during the build process, transforming your class files, or alternatively as Java agents, i.e. they perform the byte code transformation during class-loading. It depends on your use case. If I understand correctly, your use case is that other developers using your classes can see the additional fields or methods you create dynamically. In that case, you would add them during build time and they would be part of the byte code in your library or module.