Why do I have to call .toClass() after changing a method body with Javassist?

我与影子孤独终老i 提交于 2020-01-01 15:51:05

问题


I modify getMessage() method body of my TestClass by Javassist like this:

ClassPool cp = new ClassPool(true);
CtClass ctClass = cp.get("my.test.javassist.TestClass");
CtMethod ctMethod = ctClass.getDeclaredMethod("getMessage");
ctMethod.setBody("{ return \"Hello from javassist\"; }");
ctClass.toClass();

TestClass c = new TestClass();
System.out.println(c.getMessage());

It works well. However, if I remove the ctClass.toClass() method call, the body substitution doesn't work. Why?

How should I correctly replace the body of my getMessage() method? Am I doing it right?


回答1:


A ClassPool contains CtClass objects - they represent classes but they are not java classes. The toClass() methods convert CtClass instances into java classes and actually load the class.

If you do not execute toClass(), then the byte code changes will not be compiled into the class and new TestClass() will trigger a classload from the classpath.



来源:https://stackoverflow.com/questions/7385789/why-do-i-have-to-call-toclass-after-changing-a-method-body-with-javassist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!