I'm a newbie to Javassist, and I've already read some tutorials related to it.
Because I need do some bytecode injection in each method enter or before the method exit, and get some statistics from this.
Through the online javassit tutorial, I find that we can make a new field to an existing class:
CtClass point = ClassPool.getDefault().get("Point");
CtField f = new CtField(CtClass.intType, "z", point);
point.addField(f);
But the type of the CtField only contains primitive type by default, can we add a new field whose type is non-primitive, for instance, ArrayList?
If I can add the new ArrayList field to the existing class, since the class doesn't import java.util.ArrayList, will it cause compile error?
Yes, you can add non-primitive fields. You just need to get a handle to the class for the field, normally via ClassPool. Note that you will need the fully qualified 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With