簡體   English   中英

Sonarqube:編寫自定義Java規則時如何獲取表達式字符串?

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

目標類是:

class Example{

  public void m(){

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

  }

}

我想獲取MethodInvocation“ System.out.println(” Hello“ + 1)”的完整字符串以進行某些正則表達式檢查。 怎么寫?

public class Rule extends BaseTreeVisitor implements JavaFileScanner {

    @Override
    public void visitMethodInvocation(MethodInvocationTree tree) {

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

    }
}

我使用eclipse jdt和idea psi編寫了一些代碼檢查規則,它們的表達式樹節點具有這些屬性。 我想知道為什么聲納只有第一個和最后一個令牌。

謝謝!

一個老問題,但是我有一個解決方案。

這適用於任何種類的樹。

@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();
}

如果要進一步完善,還可以使用firstToken()。column或在正則表達式中使用方法名稱。

如果要增加行數/擴大范圍,只需使用該樹的父樹tree.parent()

這還將處理表達式/參數/等跨越多行的情況。

也許有更好的方法...但是我不知道其他任何方法。 如果我發現更好的話,可能會更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM