我正在尝试在插入方法时调用局部变量。到目前为止,我能够在Node中获取局部变量,但实际上无法访问任何内容。
这是我的插入内容(非常草率,我已经有一段时间了,一段时间前设计不再是我的主要任务):
final ClassReader reader = new ClassReader("revel/reflection/test/SomeClass");
final ClassNode classNode = new ClassNode();
reader.accept(classNode, 0);
for(final MethodNode mn : (List<MethodNode>)classNode.methods) {
if(mn.name.equalsIgnoreCase("testLocals")) {
final InsnList list = new InsnList();
for(final LocalVariableNode local : (List<LocalVariableNode>)mn.localVariables) {
System.out.println("Local Variable: " + local.name + " : " + local.desc + " : " + local.signature + " : " + local.index);
if(local.desc.contains("String")) {
mn.visitVarInsn(Opcodes.ALOAD, local.index);
final VarInsnNode node = new VarInsnNode(Opcodes.ALOAD, 1);
list.add(node);
System.out.println("added local var '" + local.name + "'");
}
}
final MethodInsnNode insertion = new MethodInsnNode(Opcodes.INVOKESTATIC, "revel/reflection/test/Test", "printLocalString", "(Ljava/lang/String;)V");
list.add(insertion);
mn.instructions.insert(list);
}
}
ClassWriter writer = new ClassWriter(0);
classNode.accept(writer);
loadClass(writer.toByteArray(), "revel.reflection.test.SomeClass");
SomeClass.testLocals(true);
尝试进入的方法:
public static void testLocals(boolean one) {
String two = "hello local variables";
one = true;
int three = 64;
}
它产生:
Local Variable: one : Z : null : 0
Local Variable: two : Ljava/lang/String; : null : 1
added local var 'two'
Local Variable: three : I : null : 2
Exception in thread "main" java.lang.VerifyError: Bad local variable type
Exception Details:
Location:
revel/reflection/test/SomeClass.testLocals(Z)V @0: aload_1
Reason:
Type top (current frame, locals[1]) is not assignable to reference type
Current Frame:
bci: @0
flags: { }
locals: { integer }
stack: { }
Bytecode:
0000000: 2bb8 0040 1242 4c04 3b10 403d b12b
at revel.reflection.test.Test.main(Test.java:66)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
第66行是SomeClass.testLocals(true); 任何人都可以阐明情况吗?
看来您的问题出在mn.instructions.insert(list);
哪行上,该行将新指令插入到该方法的所有指令列表的开头testLocals
。换句话说,您已经two
在声明或分配值之前使用了变量。尝试使用mn.instructions.add(list);
并查看是否能解决问题。
祝你好运!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句