java - 使用 ASM 获取方法参数

标签 java reflection java-bytecode-asm

我找到了一些示例,这些示例向我展示了使用 MethodAdapter 进行某些方法调用的位置:

public void visitMethodInsn(int opcode, String owner, String name, String desc) {
        if (owner.equals(targetClass)
                && name.equals(targetMethod.getName())
                && desc.equals(targetMethod.getDescriptor())) {
            callsTarget = true;
        }
  }

我需要参数,例如,如果我有 object.getText("mykey") 我想获取文本“mykey”。

这可能吗?

最佳答案

我有一个framework您可能会发现它很有用(特别是 procyon-compilertools )。它将使您能够以比 ASM 更面向对象的方式完成您所要求的事情。然而,该项目仍处于开发早期,可能会发生变化,因此我不建议在生产项目中使用它。

您可以以此为起点:

public class CallInspectionSample {
    static class Target {
        public static void main(String[] args) {
            new Target().getText("MyKey");
        }

        public String getText(final String key) {
            return null;
        }
    }

    public static void main(String[] args) {
        final TypeReference targetType = MetadataSystem.instance().lookupType("CallInspectionSample$Target");
        final TypeDefinition resolvedType = targetType.resolve();
        final MethodDefinition mainMethod = resolvedType.getDeclaredMethods().get(1);
        final MethodDefinition getTextMethod = resolvedType.getDeclaredMethods().get(2);

        final MethodBody mainBody = mainMethod.getBody();

        final Block methodAst = new Block();
        final DecompilerContext context = new DecompilerContext();

        context.setCurrentType(resolvedType);
        context.setCurrentMethod(mainMethod);

        methodAst.getBody().addAll(AstBuilder.build(mainBody, true, context));

        AstOptimizer.optimize(context, methodAst);

        for (final Expression e : methodAst.getChildrenAndSelfRecursive(Expression.class)) {
            if (e.getCode() == AstCode.InvokeVirtual &&
                ((MethodReference) e.getOperand()).resolve() == getTextMethod) {

                // Analyze arguments here (skip first for instance methods)...
                System.out.println(e.getArguments());
            }
        }
    }
}

(示例输出 [initobject:Target(Target::<init>), ldc:String("MyKey")] )

关于java - 使用 ASM 获取方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16742880/

相关文章:

java - Mongodb数据库Schema设计技巧

java - 在 for 循环中创建多个 Google App Engine 实体

java - 没有类型信息的 JVM 调用接口(interface)

java - 我可以将什么作为第二个参数传递给 java 反射的 getMethod 以表示没有参数?

java - 多态调用: resolving target method from bytecode

java - "final"在运行时是最终的吗?

java - 避免图像超出屏幕(Android)(libGDX)

java - 我们可以将多个参数传递给 RestCypherQueryEngine.query 吗?

c# - 获取 PropertyInfo 的值

java - 如果代码将被混淆,我是否可以始终使用反射 API?