Javassist: Initializing a static class field for a given value?

I would like to bind some instance of the object to a class created using Javassist. This object is read from some source, data is not known in advance.

// Create the class. CtClass subClass = pool.makeClass( fullName ); final CtClass superClass = pool.get( Foo.class.getName() ); subClass.setSuperclass( superClass ); // Add a static field containing the definition. // Probably unachievable. final CtClass defClass = pool.get( SomeMetaData.class.getName() ); CtField defField = new CtField( defClass, "DEF", subClass ); defField.setModifiers( Modifier.STATIC ); subClass.addField( CtField.Initializer.??? ); return subClass.toClass(); 

But when I checked the API, it seems that the Javassist is creating real bytecode that stores the initialization in terms of “call it” or “instantiate it” or “use this constant”.

Is there a way to ask Javassist to add a static field initialized by an existing instance specified at runtime?

+4
source share
1 answer

You can specify the initializer as follows:

 // Create the class. CtClass subClass = pool.makeClass( fullName ); final CtClass superClass = pool.get( Foo.class.getName() ); subClass.setSuperclass( superClass ); // Add a static field containing the definition. // Probably unachievable. final CtClass defClass = pool.get( SomeMetaData.class.getName() ); CtField defField = new CtField( defClass, "DEF", subClass ); defField.setModifiers( Modifier.STATIC ); subClass.addField( defField, CtField.Initializer.byNew(defClass) ); return subClass.toClass(); 

This is equivalent to creating the following

 class fullName extends Foo { static SomeMetaData DEF = new SomeMetaData(); } 
+3
source

Source: https://habr.com/ru/post/1487985/


All Articles