访问ASM Java库中的局部变量

我正在尝试在插入方法时调用局部变量。 到目前为止,我能够在Node中获取局部变量,但实际上无法访问任何东西。

这是我的插入内容(它非常糟糕,我已经在这一段时间了,设计在不久前停止了我的主要优先事项):

final ClassReader reader = new ClassReader("revel/reflection/test/SomeClass"); final ClassNode classNode = new ClassNode(); reader.accept(classNode, 0); for(final MethodNode mn : (List)classNode.methods) { if(mn.name.equalsIgnoreCase("testLocals")) { final InsnList list = new InsnList(); for(final LocalVariableNode local : (List)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); 并看看是否不能解决问题。

祝你好运!