4

我能够使用以下代码获取类级别变量的声明。但我只需要变量名。这是我为以下代码得到的输出 - [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);
    }
  }
}
4

2 回答 2

3

您可以使用以下简单的正则表达式:

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

然后可以编译成Pattern

final Pattern pattern = Pattern.compile(regex);

然后最后在 a 中使用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);
    }
}
于 2018-06-04T13:05:48.487 回答
2

你可以试试这个。如果 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());
    }
} 
于 2018-06-05T10:16:29.087 回答