开发者

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

开发者 https://www.devze.com 2023-04-04 10:07 出处:网络
I modify getMessage() method body of my TestClass by Javassist like this: ClassPool cp = new ClassPool(true);

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号