【问题标题】:super class not assignable to class implemented during runtime by asm超类不可分配给 asm 在运行时实现的类
【发布时间】:2015-05-11 17:59:18
【问题描述】:

我有一个包含内部接口的 java 类,并计划在运行时使用 asm 字节码注入来实现实现类。

package my.example;
public class X{
    public static interface XInt{
        public void getX();
    }
    //the following class that implement the interface will be defined during runtime.
    //I put it here just to show how the implementation will look like
    public static XImpl extend Y implements XInt{
        public void getX(){//implementation code}
    }
}

我确定我的 asm 代码是正确的,但是在定义类并调用 Class.forName("my.example.X$XImpl") 之后,我收到以下错误:

> Bad <init> method call
Exception Details:
  Location:
    my/example/X$XImpl.<init>()V: invokespecial
  Reason:
    Type 'my/other/package/Y' is not assignable to 'my/example/X$XImpl'

我的猜测是 Y 类在运行时还不可用?我不知道.. 任何帮助将不胜感激!

编辑: 我加载XImpl的方式很简单:

defineClass("my.example.X$XImpl", getXImplByte());
Class.forName("my.example.X$XImpl"); //fails here

我之所以确定我的字节码和类加载方法是正确的,因为如果我定义实现类而不扩展任何其他类,它会正常工作

【问题讨论】:

  • 能否请您发布您如何定义和实例化 XImpl 实例?看起来像典型的类加载问题
  • @qwwdfsad 嗨,我已经编辑了我的问题。感谢您的回复

标签: java runtime java-bytecode-asm dynamic-class-creation


【解决方案1】:

似乎 ASM 类加载器不是 X 类加载器的子类,因此有两个不同的类(即使它们相同),它们不能相互转换。

尝试使用:

Method m = ClassLoader.getDeclaredMethods("defineClass", String.class, byte[].class, int.class, int.class);
m.setAccessible(true);
m.invoke(X.class.getClassLoader(), ...);

【讨论】:

  • 谢谢!显然我有一些内部问题,你的回答给了我一个很好的方向
  • 您能说说问题吗?我很有趣,还有什么可能导致这个错误
  • 我有自己的类加载器实现,它覆盖/扩展了一些功能。当您弄乱 Java 类路径并进行动态绑定时,事情开始变得非常有趣..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-28
  • 2020-04-02
  • 2023-04-04
  • 2019-06-02
  • 2021-10-29
  • 2021-05-22
相关资源
最近更新 更多