Reputation: 345
I have been trying out Javassist but found that even the most simple use cases, the first example from the Javassist official tutorial does not appear to work https://www.javassist.org/tutorial/tutorial.html
I'm not sure why when I try the following the superclass does not appear to change. No exceptions are thrown but when I log from within each of the constructor's of my class hierarchy the Rectangle class does not end up extending the ColorShape class.
I've modified my example slightly from the javassist tutorial as the documentation for setSuperclass() says...
"Changes a super class unless this object represents an interface. The new super class must be compatible with the old one; for example, it should inherit from the old super class"
public class RuntimeModifier {
public void changeSuperClass() {
ClassPool pool = ClassPool.getDefault();
pool.insertClassPath(new ClassClassPath(this.getClass()));
CtClass cc = null;
try {
cc = pool.get("org.example.Rectangle");
cc.setSuperclass(pool.get("org.example.ColorRectangle"));
cc.writeFile();
} catch (NotFoundException e) {
System.out.println("NotFoundException: ");
throw new RuntimeException(e);
} catch (CannotCompileException e) {
System.out.println("CannotCompileException");
throw new RuntimeException(e);
} catch (IOException e) {
System.out.println("IOException");
throw new RuntimeException(e);
}
System.out.println("called change super class");
}
public class Rectangle extends Shape{
Rectangle(){
System.out.println("Rectangle Created");
}
}
public class ColorRectangle extends Shape{
ColorRectangle(){
System.out.println("ColorRectangle created");
}
}
public class Main {
public static void main(String[] args) {
RuntimeModifier rm = new RuntimeModifier();
rm.changeSuperClass();
Rectangle myRect = new Rectangle();
}
}
OutPut:
called change super class
Shape Created
Rectangle Created
....
I would expect to see this but I don't
called change super class
Shape Created
ColorRectangle created
Rectangle Created
It looks like the new superclass for Rectangle "ColorRectangle" is not created, Why is this?
Upvotes: 0
Views: 91
Reputation: 11
I meet the same issue and then this situation is work, make the ctClass.toClass()
and the invoke the constructor:
Class<?> clazz = ctClass.toClass();
Object obj = clazz.newInstance();
Upvotes: 1