ClassWriter cw = new ClassWriter(...);
byte[] bytes = cw.toByteArray();
我想从bytes
数组创建新的类实例。我该怎么做呢?有可能吗?
ClassWriter cw = new ClassWriter(...);
byte[] bytes = cw.toByteArray();
我想从bytes
数组创建新的类实例。我该怎么做呢?有可能吗?
这是可能的,您需要使用反射来实现这一点。伪代码是:
final Class clazz = loadIntoCurrentClassLoader(bytes); //I'm assuming you wrote this already using defineClass
final YourClass foo ;
try {
foo = (YourClass) clazz.newInstance();
}
catch (final Exception e) {
throw new RuntimeException(e);
}
我可以通过扩展 ClassLoader 并使用 defineClass 来创建类。但是随后创建的类将我的扩展类加载器作为其类加载器,当我的类的代码加载其他类时会导致失败。大概我可以通过创建我的 ClassLoader 以正确的方式委派所有内容来解决这个问题,但如何做到这一点并不明显。