如何获取方法调用返回的字段

How to get the field returned by a method invocation

我正在为 java 编写自定义 SonarQube 规则,我想在其中检查创建的对象是否使用具有特定注释的参数。

我正在测试的文件

class MyClass {

  public void doSomething() {
    final var v = new Dto();
    new MyObject(v.value1()); // Compliant since value1 has @MyAnnotation
    new MyObject(v.value2()); // Noncompliant
  }

  public static class MyObject {

    private final String value;

    public MyObject(String value) {
      this.value = value;
    }

  }

  @Target(ElementType.FIELD)
  @Retention(RetentionPolicy.RUNTIME)
  public @interface MyAnnotation {
  }

  public static class Dto {

    @MyAnnotation
    private String value1;
    private String value2;

    public String value1() {
      return this.value1;
    }

    public String value2() {
      return this.value2;
    }
  }
}

支票

public class MyObjectCheck extends IssuableSubscriptionVisitor {

  @Override
  public List<Kind> nodesToVisit() {
    return Collections.singletonList(Kind.NEW_CLASS);
  }

  @Override
  public void visitNode(Tree tree) {
    NewClassTree ctor = (NewClassTree) tree;
    if(!ctor.identifier().symbolType().name().contains("MyObject")) { //to change
      return;
    }
    if(ctor.arguments().size() == 1) {
      final ExpressionTree expressionTree = ctor.arguments().get(0);
      if(expressionTree.is(Kind.METHOD_INVOCATION)) {
        MethodInvocationTree methodInvocation = (MethodInvocationTree) expressionTree;

      }
    }
  }
}

methodInvocation 开始,我可以设法调用 methodSelect 以获得 MethodInvocationTree,但我不知道如何转到该方法返回的字段。

我不得不做出让步,我认为调用的方法的 class 是 POJO 或 java 记录。这样我就能够获取链接字段和注释:

        String methodName = methodInvocationTree.symbol().name();
        final Symbol.TypeSymbol methodClass = (Symbol.TypeSymbol) methodInvocationTree.symbol().owner();
        final List<SymbolMetadata.AnnotationInstance> annotations = methodClass.lookupSymbols(methodName).iterator().next().metadata().annotations();