ClassCast Exception is thrown after I've used ASM Toolkit to replace the body of a static method
I've been trying to use the ASM bytecode toolkit to replace the body of a public and static method in a class. The actual body replacement seems to work fine and I do get the expected behavior if execute the following once the transformation has completed:
开发者_StackOverflow社区Class cls = loadClass("ext.hm.cmd.MyProg");
cls.getMethod("hello").invoke(instance);
However if I try to cast the new instance to MyProg like so
MyProg p = (MyProg) instance;
p.hello();
I get the error message:
java.lang.ClassCastException: ext.hm.cmd.MyProg cannot be cast to ext.hm.cmd.MyProgAs I'm not adding or deleting any methods in the class I can't really understand why I get this error. Has anyone seen this before and if so, what is the cause of it and how can I solve it?
Thanks
Daniel MartinssonKind of a guess, but I'd say you have the same named class loaded by two different ClassLoaders. Those are actually considered two separate classes and one cannot be cast to the other.
One is loaded before the line
MyProg p = (MyProg) instance;
is executed. The other is loaded through your call to loadClass
.
To fix this you would probably need the class that performs the line of code above to be loaded by the same ClassLoader that loads the altered instance of MyProg. Then it should work.
If you use spring boot dev tool, you can try exclude it from the project
精彩评论