How to create synthetic fields in java?

  • How can I create synthetic fields in Java?

  • Is it possible to create synthetic fields in java at runtime? If not: is there a method compatible with the standard at compile time (without changing some bytes in the class file).

+7
java reflection
source share
2 answers

They are created by the compiler when they require the "strangeness" of the language. A simple example of this is using an inner class:

public class Test { class Inner { } } 

The Test.Inner class will have a synthetic field to represent the corresponding instance of the Test class.

We can extend this code a bit to show this field:

 import java.lang.reflect.*; public class Test { public static void main(String[] args) { for (Field field : Inner.class.getDeclaredFields()) { System.out.println(field.getName() + ": " + field.isSynthetic()); } } class Inner { } } 

With my compiler that prints:

 this$0: true 
+14
source share

Yes, it is doable, and this is called weaving at boot time. Essentially, you will need to define your own ClassLoader, which will decide for each class if it is necessary to modify the class file that needs to be loaded; this means that you will need to check the loadable binary class, perhaps change it and then pass it to the JVM for definition / resolution. This is a bit cumbersome, complex, and prone to ClassCastExceptions (the same class defined in two different classloaders will produce 2 different classes that are not compatible with the destination).

Please note that weaving allows you to do much more: you can add new methods, interfaces, fields, change the code of existing classes, etc.

There are already tools that can help you - see, for example, AspectJ as a complete modification of the language or something like BCEL or javassist, which allows you to write such tools for weaving.

+3
source share

All Articles