0

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?

kriegaex
  • 63,017
  • 15
  • 111
  • 202
aminbhst
  • 75
  • 7
  • It sounds like you know what their names are going to be, for you to access them, so why not just declare them normally? – Louis Wasserman Apr 12 '22 at 19:43
  • @LouisWasserman because it is supposed to be a library and the point is that the developer who is using it can just access the information like the table name and property names without having to declare all of them explicitly. I want all of these to be automated and added to the class. besides I'm genuinely curious about how lombok does this and how I can implement something like it myself. – aminbhst Apr 12 '22 at 19:54
  • You can use an annotation processor with javac which allows you to alter the generated code during compilation itself. I've never used it myself, and so I don't know how effective it might be in your use case. Otherwise, you can write an instrumentation agent, which allows you to alter bytecode as classes get loaded into the JVM. ByteBuddy might be helpful for this kind of thing. – boneill Apr 12 '22 at 19:59
  • 1
    Well, annotation processors can only add additional (on-the-fly created) java files to the compilation process. It's not possible to modify any existing classes. – Johannes Kuhn Apr 12 '22 at 21:38
  • Last I checked, Lombok was a huge pile of hacks, hacking into the compiler to make it think extra fields were there. You should probably not copy what it does. AspectJ is a language designed to do this sort of thing. – user253751 Jun 02 '22 at 17:00

1 Answers1

1

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.

kriegaex
  • 63,017
  • 15
  • 111
  • 202