Java System类的插入



我是仪器仪表的新手。稍后,我需要在其中一个引导程序类java.lang.String中添加一个静态变量,也许还需要一个静态方法。我尝试了Javassist和ASM,但都报告了错误

> Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(Unknown Sou
rce)
at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(Unknown So
urce)
Caused by: java.lang.UnsupportedOperationException: class redefinition failed: a
ttempted to change the schema (add/remove fields)
at sun.instrument.InstrumentationImpl.retransformClasses0(Native Method)
at sun.instrument.InstrumentationImpl.retransformClasses(Unknown Source)

这是我的转换方法和ASM代码,

public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
ProtectionDomain domain, byte[] classfileBuffer) 
{
if (className.startsWith("java/lang/String")) {
try {
classfileBuffer = modifyField(classfileBuffer);
} catch (Exception e) {
e.printStackTrace();
}
return classfileBuffer
}
public static byte[] modifyField(byte[] origClassData) throws Exception {
ClassReader cr = new ClassReader(origClassData);
final ClassWriter cw = new ClassWriter(cr, ASM5);
// add the static final fields
cw.visitField(ACC_PUBLIC + ACC_FINAL + ACC_STATIC, "bVal","Z", null, new Boolean("false")).visitEnd();
// wrap the ClassWriter with a ClassVisitor that adds the static block to
// initialize the above fields
ClassVisitor cv = new CustomVisitor(ASM5, cw);
// feed the original class to the wrapped ClassVisitor
cr.accept(cv, 0);
// produce the modified class
byte[] newClassData = cw.toByteArray();
return newClassData;
}

我还将"可以重新定义类"one_answers"可以重新转换类"都设置为TRUE。

感谢您的帮助

JVM不允许添加字段或对类文件格式进行任何其他更改,正如异常所示。OpenJDK的一些特殊构建(如动态代码进化JVM(允许这样做,但大多数JVM不支持这样做。

我以前也遇到过同样的问题。我可以向你指出我的问题,这可能对你有所帮助。

使用Javassist,您可以修改本机方法的主体,但不能添加方法或字段。看看这个问题:Java代理无法转换我的项目中的所有类

相关内容

最新更新