jvm 为什么Javassist setSuperclass()看起来不起作用?

laximzn5  于 2022-11-23  发布在  Java
关注(0)|答案(1)|浏览(78)

我一直在尝试使用Javassist,但发现即使是最简单的用例,Javassist官方教程中的第一个示例似乎也无法运行https://www.javassist.org/tutorial/tutorial.html
我不知道为什么当我尝试执行以下操作时,超类似乎没有变化。没有抛出异常,但是当我从类层次结构的每个构造函数中登录时,Rectangle类并没有扩展ColorShape类。
我对javassist教程中的示例做了一些修改,因为setSuperclass()的文档中说...
"* 更改超类,除非此对象表示接口。新的超类必须与旧的兼容;例如,它应该继承自旧的超类 *"

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();
}

}
输出:

called change super class
Shape Created
Rectangle Created

....
我希望看到这个,但我没有

called change super class
Shape Created 
ColorRectangle created 
Rectangle Created

看起来好像没有创建矩形的新超类"ColorRectangle",这是为什么?

rdlzhqv9

rdlzhqv91#

我遇到同样的问题,然后这种情况就起作用了,make the ctClass.toClass()和the invoke the constructor:

Class<?> clazz = ctClass.toClass();
Object obj = clazz.newInstance();

相关问题