我使用 ASM Toolkit 替换静态方法的主体后抛出 ClassCast 异常

发布于 2024-09-30 03:24:44 字数 492 浏览 0 评论 0原文

我一直在尝试使用 ASM 字节码工具包来替换类中公共和静态方法的主体。实际的主体替换似乎工作正常,如果在转换完成后执行以下命令,我确实会得到预期的行为:

Class cls = loadClass("ext.hm.cmd.MyProg");
cls.getMethod("hello").invoke(instance);

但是,如果我尝试将新实例转换为 MyProg,就像这样,

MyProg p =  (MyProg) instance;
p.hello();

我会收到错误消息:
java.lang.ClassCastException: ext.hm.cmd.MyProg 无法转换为 ext.hm.cmd.MyProg

由于我没有在类中添加或删除任何方法,所以我无法真正理解为什么会出现此错误。以前有人见过这个吗?如果是的话,其原因是什么,我该如何解决?

谢谢
丹尼尔·马丁森

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:

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.MyProg

As 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 Martinsson

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你的背包 2024-10-07 03:24:44

有点猜测,但我想说你有由两个不同的类加载器加载的相同命名的类。这些实际上被视为两个独立的类,并且不能将一个类转换为另一个类。

该行之前加载一个

 MyProg p =  (MyProg) instance;

在执行 。另一个是通过调用 loadClass 加载的。

要解决此问题,您可能需要由加载更改后的 MyProg 实例的相同类加载器加载执行上述代码行的类。那么它应该可以工作。

Kind 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.

一枫情书 2024-10-07 03:24:44

如果您使用 spring boot dev tool,可以尝试将其从项目中排除

If you use spring boot dev tool, you can try exclude it from the project

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文