简体   繁体   中英

Sonarqube: How to get the expression string when writing custom java rules?

The target class is:

class Example{

  public void m(){

    System.out.println("Hello" + 1);

  }

}

I want to get the full string of MethodInvocation "System.out.println("Hello" + 1)" for some regex check. How to write?

public class Rule extends BaseTreeVisitor implements JavaFileScanner {

    @Override
    public void visitMethodInvocation(MethodInvocationTree tree) {

        //get the string of MethodInvocation
        //some regex check
        super.visitMethodInvocation(tree);

    }
}

I wrote some code inspection rules using eclipse jdt and idea psi whose expression tree node has these attributes. I wonder why sonar's just has first and last token instead.

Thanks!

An old question, but I have a solution.

This works for any sort of tree.

@Override
public void visitMethodInvocation(MethodInvocationTree tree) {
    int firstLine = tree.firstToken().line();
    int lastLine = tree.lastToken().line();

    String rawText = getRelevantLines(firstLine, lastLine);
    // do your thing here with rawText
}

private String getRelevantLines(int startLine, int endLine) {
    StringBuilder builder = new StringBuilder();
    context.getFileLines().subList(startLine, endLine).forEach(builder::append);
    return builder.toString();
}

If you want to refine further, you can also use firstToken().column or perhaps use the method name in your regex.

If you want more lines/bigger scope, just use the parent of that tree tree.parent()

This will also handle cases where the expression/params/etc span multiple lines.

There might be a better way... but I don't know of any other way. May update if I figure out something better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM