声纳自定义规则:禁用'system.out.println'

时间:2017-08-18 02:14:48

标签: java sonarqube sonar-runner sonarqube-scan sonarlint

我的目标是:当java文件包含System.out.println()

时引发问题

规则代码剪断:

public void visitNode(Tree tree) {
     //ohter code
     MethodMatcher matcher = MethodMatcher.create()
                .typeDefinition(TypeCriteria.anyType())
                .name("println")
                .withoutParameter();

    MethodInvocationTree methodInvocationTree = isTreeMethodInvocation(expressionTree.expression(), matcher);
    if(methodInvocationTree != null){
      reportIssue(tree, "msg");
    }
}
private static MethodInvocationTree isTreeMethodInvocation(ExpressionTree tree, MethodMatcher matcher) {
  Tree expression = ExpressionUtils.skipParentheses(tree);
  if (expression.is(Tree.Kind.METHOD_INVOCATION)) {
    MethodInvocationTree methodInvocation = (MethodInvocationTree) expression;
    if (matcher.matches(methodInvocation)) {
      return methodInvocation;
    }
  }
  return null;
}

测试用例代码:

public class SaasDisableSystemOutPrintCheckCase {
   public void test() {
        test2222();
        System.out.println("aaa");
   }

   public void test2222() {} // Noncompliant
}
它不起作用? 但改变这样的代码:

MethodMatcher matcher = MethodMatcher.create()
//.typeDefinition(TypeCriteria.is("java.io.PrintStream"))
                .name("test2222")
                .withoutParameter();

这是正确的!

如何使用MethodMatcher检测特殊表达式?

谢谢

0 个答案:

没有答案