如何使用 Java Tree Compiler API 找到标识符的类型声明? [英] How do I find the type declaration of an identifier using the Java Tree Compiler API?
本文介绍了如何使用 Java Tree Compiler API 找到标识符的类型声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个变量/标识符的名称,比如 x
,以及 JCCompilationUnit
和 Scope
.有没有办法找到x
的类型?
I have the name of a variable/identifier, say, x
, and the JCCompilationUnit
and Scope
. Is there a way to find the type of x
?
推荐答案
public Symbol getSymbol(CompilationUnitTree cut, JCStatement stmt, List<JCExpression> typeParams, Name varName, List<JCExpression> args) {
java.util.List<Type> typeSyms = getArgTypes(typeParams, cut, stmt);
java.util.List<Type> argsSyms = getArgTypes(args, cut, stmt);
final Scope scope = getScope(cut, stmt);
Symbol t = contains(scope, typeSyms, varName, argsSyms); //first lookup scope for all public identifiers
TypeElement cl = scope.getEnclosingClass();
while (t == null && cl != null) { //lookup hierarchy for inacessible identifiers too
t = contains(elementUtils.getAllMembers(cl), typeSyms, varName, argsSyms);
final TypeMirror superclass = cl.getSuperclass();
if (superclass != null) {
cl = (TypeElement) ((Type) superclass).asElement();
}
}
return t;
}
public Symbol getSymbol(Name varName, Symbol accessor, CompilationUnitTree cut, JCStatement stmt) {
if (varName.contentEquals("class")) {
Symbol javaLangClassSym = getSymbol(cut, stmt, null, elementUtils.getName("java.lang.Class"), null);
JCIdent id = tm.Ident(javaLangClassSym);
JCExpression mName = tm.Select(id, elementUtils.getName("forName"));
JCLiteral idLiteral = tm.Literal(accessor.toString());
JCMethodInvocation mi = tm.Apply(List.<JCExpression>nil(), mName, List.<JCExpression>of(idLiteral));
Symbol s = getSymbol(mi, cut, stmt);
return s;
}
accessor = getTypeSymbol(accessor);
java.util.List<Symbol> enclosedElements = getEnclosedElements(accessor, cut, stmt);
Symbol s = contains(enclosedElements, null, varName, null);
return s;
}
我最终写了一个完整的具有解析方法的类.继承它,或传入 TreeMaker(和其他参数),它可以是静态的.如果有人觉得值得,欢迎提供补丁.
I ended up writing a full class with resolving methods. Inheriting it, or passing in the TreeMaker (and other parameters) it can be made static. Should someone find it worthwile, a patch is welcome.
这篇关于如何使用 Java Tree Compiler API 找到标识符的类型声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文