【发布时间】:2021-11-29 16:56:03
【问题描述】:
我正在为 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,但我不知道如何转到该方法返回的字段。
【问题讨论】:
-
Java 总是按值传递。该方法不返回字段,它返回一个值。