JDK1.6,修改jvm中动态加载的类。当我对代码classReader.accept(classAdapter, ClassReader.SKIP_DEBUG);
发表评论时,异常"UnsupportedOperationException"
会消失。
实际上,为了测试我的代码,我没有修改任何字段或方法。但是,在调用"UnsupportedOperationException"
之后,程序会捕获异常retransformClasses()
。有人有类似的例外吗?可以给我一些建议吗?谢谢
代码如下:
public byte[] modifySleepMethod() throws Exception {
System.out.println("Call modifySleepMethod");
ClassReader classReader = new ClassReader(classfileBuffer);
System.out.println("new classreader");
ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
System.out.println("new classwriter");
ClassAdapter classAdapter = new ModifyMethodClassAdapter(classWriter);
classReader.accept(classAdapter, ClassReader.SKIP_DEBUG);
byte[] classFile = null;
classFile = classWriter.toByteArray();
FileOutputStream fos;
try {
fos = new FileOutputStream("D:\\testfos\\b\\Example2.class");
System.out.println("ddddddmodifymethodtest");
fos.write(classFile);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
return classFile;
}
}
|
protected void transform(Class<?> clazz, ClassLoader classLoader) {
DemoTransformer dt = new DemoTransformer(clazz.getName(), classLoader);
instrumentation.addTransformer(dt, true);
try {
instrumentation.retransformClasses(clazz);
} catch (Exception ex) {
throw new RuntimeException("Failed to transform [" + clazz.getName() + "]", ex);
}