Is it possible to add a non-primitive field to an existing class using javassist?

I am new to Javassist and I already read some lessons related to it.

Since I need some kind of bytecode injection in each method to be injected or before the method exits, and get some statistics from this.

Through the javassit online tutorial, I discovered that we can create a new field for an existing class:

CtClass point = ClassPool.getDefault().get("Point"); CtField f = new CtField(CtClass.intType, "z", point); point.addField(f); 

But the CtField type by default contains only a primitive type, is it possible to add a new field whose type is not primitive, for example ArrayList?

If I can add a new ArrayList field to an existing class, since the class does not import java.util.ArrayList, will this cause a compilation error?

+6
source share
1 answer

Yes, you can add non-primitive fields. You just need to get the class handle for the field, usually through ClassPool. Note that you will need the full name of the class you want to use:

 CtClass arrListClazz = ClassPool.getDefault().get("java.util.ArrayList"); CtClass point = ClassPool.getDefault().get("Point"); CtField f = new CtField(arrListClazz, "someList", point); point.addField(f); 
+7
source

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


All Articles