我的目标是:当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
检测特殊表达式?
谢谢