gpt4 book ai didi

java - 如何使用ASM框架访问匿名内部类

转载 作者:太空宇宙 更新时间:2023-11-04 11:41:03 26 4
gpt4 key购买 nike

例如,我需要在代码编译后访问run()中的信息。

Class A{
public static void main(String[] args){
new Thread(new Runnable() {
@Override
public void run() {
//something
}
}).start();
}
}

我扩展了ASM ClassVisitor,如何访问匿名内部类中的信息。

public class MyClassVisitor extends ClassVisitor {

public MyClassVisitor(final ClassVisitor cv) {
super(Opcodes.ASM5, cv);
}

@Override
public void visit(int version, int access, String name, String signature,
String superName, String[] interfaces) {
if (cv != null) {
cv.visit(version, access, name, signature, superName, interfaces);
}
}

@Override
public void visitInnerClass(String name, String outerName, String innerName, int access) {
//how should I do to access the information in an anonymous inner class
super.visitInnerClass(name, outerName, innerName, access);
}
}

最佳答案

你知道匿名内部类编译后的名称如Main$1。基于这个事实,我们可以通过重写visitMethod来访问方法信息。

代码如下。

public class MyClassVisitor extends ClassVisitor {

private String ownerClassName;

public MyClassVisitor(final ClassVisitor cv) {
super(Opcodes.ASM5, cv);
}

@Override
public void visit(int version, int access, String name, String signature,
String superName, String[] interfaces) {
if (cv != null) {
cv.visit(version, access, name, signature, superName, interfaces);
ownerClassName = name;
}
}

@Override
public MethodVisitor visitMethod(int access, String name, String desc,
String signature, String[] exceptions) {
MethodVisitor mv = cv.visitMethod(access, name, desc, signature,
exceptions);
//the name of anonymous inner class after compiled was like this: Main$1
String[] array = ownerClassName.split("$");
boolean isNumber = false;
if(array.length > 1){
isNumber = array[array.length - 1].matches("[0-9]+");
}
//if it's an anonymous inner class and the method was not construction method
if(isNumber && !name.equals("<init>")){
//return my custom MethodVisitor to parse the method information
return new MyMethodVisitor(mv);
}
return mv;
}
}

关于java - 如何使用ASM框架访问匿名内部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42779651/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com