对于编译器项目,我必须在 Java 文件中找到模式。例如,如果我输入“@x = 3”,则程序必须返回 3 归因于某物的所有情况。
为此,我使用 ASTParser来自 JDT。我解析文件并获取 CompilationUnit 对象,如下所示:
private static CompilationUnit getAST(char[] unit){
ASTParser parser = ASTParser.newParser(AST.JLS8);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(unit); // set source
parser.setResolveBindings(true); // we need bindings later on
parser.setBindingsRecovery(true);
Map options = JavaCore.getOptions();
parser.setCompilerOptions(options);
CompilationUnit cu = (CompilationUnit) parser.createAST(null);
return cu;
}
现在,我正在做的是根据给定的模式构建另一个 AST。上面的例子会产生如下结果:
AssignementExpression
LHS
Pattern("@x")
RHS
Literal("3")
然后我使用这个 AST 来搜索 CompilationUnit。问题是 ASTParser API class搜索节点需要知道我正在访问的节点的类。
我需要创建一个新的访问者对象并定义我想要在访问函数中执行的操作:
ASTVisitor visitor = (new ASTVisitor() {
public boolean visit(VariableDeclarationFragment node) {
// what I want to do
return true; // do not continue
}
}
所以我想做的是,在运行时,将AssignementExpression与VariableDeclarationFragment关联起来,并用VariableDeclarationFragment调用访问函数。像这样的东西:
Class nodeType = getTypeFromGrammar("AssignementExpression");
ASTVisitor visitor = (new ASTVisitor() {
public boolean visit(nodeType node) { // use the class that was returned above
// what I want to do
return true; // do not continue
}
}
最佳答案
一种方法是使用反射。
您需要使用 ASTVisitor 的命名子类而不是匿名类。假设它名为 MyAstVisitor。它可以重写多个 ASTVisitor.visit(T)
方法。
您可以通过 Class.getMethod() 获取适当的方法。例如:
Method visitMethod = MyASTVistor.class.getMethod( "visit", nodeType );
然后您可以使用 Method.invoke() 调用该方法:
visitMethod.invoke( myAstVisitorInstance, myNode );
关于java - 如何动态设置函数参数的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43943093/