Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we add a non-primitive field to an existing class using javassist?

Tags:

java

javassist

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?

like image 529
LifeOnCodes Avatar asked Feb 19 '12 07:02

LifeOnCodes


1 Answers

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);
like image 61
Perception Avatar answered Nov 15 '22 01:11

Perception