代码如下,就是对外部的一个包中的类用asm改变内容后,想加载后重新生成对象,但是运行后报错:
Exception in thread "main" java.lang.ClassCastException: TestJar.TestClassOne cannot be cast to TestJar.TestClassOne
import java.io.IOException;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import TestJar.TestClassOne;
public class SomeTest {
static class MyClassLoader extends ClassLoader {
public Class defineClass(String name, byte[] b) {
return defineClass(name, b, 0, b.length);
}
}
public static void main(String []args) throws IOException, InstantiationException, IllegalAccessException{
ClassReader cr=new ClassReader(TestClassOne.class.getName());
ClassWriter cw=new ClassWriter(0);
cr.accept(cw, 0);
byte b[]=cw.toByteArray();
MyClassLoader ml=new MyClassLoader();
Class clazz=ml.defineClass("TestJar.TestClassOne", b);
TestClassOne TestClassOne=(TestClassOne)clazz.newInstance();
}
}