簡體   English   中英

如何使用javaparser獲取類級變量名?

[英]How to get class level variable names using javaparser?

我能夠使用以下代碼獲取類級變量的聲明。 但我只需要變量名稱。 這是我得到以下代碼的輸出 - [private boolean flag = true;]

import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
import java.io.FileInputStream;

public class CuPrinter{
    public static void main(String[] args) throws Exception {
        // creates an input stream for the file to be parsed
        FileInputStream in = new FileInputStream("C:\\Users\\arosh\\IdeaProjects\\Bot_Twitter\\src\\MyBot.java");

        CompilationUnit cu;
        try {
            // parse the file
            cu = JavaParser.parse(in);
        } finally {
            in.close();
        }
        cu.accept(new ClassVisitor(), null);
}
private static class ClassVisitor extends VoidVisitorAdapter<Void> {
    @Override
    public void visit(ClassOrInterfaceDeclaration n, Void arg) {
        /* here you can access the attributes of the method.
         this method will be called for all methods in this
         CompilationUnit, including inner class methods */
        System.out.println(n.getFields());
        super.visit(n, arg);
    }
  }
}

您可以使用以下簡單的正則表達式:

final String regex = "^((private|public|protected)?\\s+)?.*\\s+(\\w+);$";

然后可以編譯成Pattern

final Pattern pattern = Pattern.compile(regex);

然后最終用於for-loop

for(final String field : n.getFields()){
    // create a regex-matcher
    final Matcher matcher = pattern.matcher(field);

    // if field matches regex
    if(matcher.matches()){
        // get the last group -> the fieldName
        final String name = matcher.group(matcher.groupCount());
        System.out.println("FieldName: " + name);
    }
}

你可以試試這個。 如果FieldDeclarations中有多個變量,請在內部使用一個for循環。

public void visit(ClassOrInterfaceDeclaration n, Void arg) {

    super.visit(n, arg);
    for(FieldDeclaration ff:n.getFields())
    {
        System.out.println(ff.getVariable(0).getName());
    }
} 

暫無
暫無

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

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