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
ClassPoolcontainsCtClassobjects – they represent classes but they are not java classes. ThetoClass()methods convertCtClassinstances 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 andnew TestClass()will trigger a classload from the classpath.