我正在尝试使用ASTVisitor
获取变量的构造函数。
public boolean visit(VariableDeclarationFragment node)
{
IVariableBinding variableBinding = node.resolveBinding();
// I can't seem to get the constructor here
}
样品
Base b = new Derived(); // How do I get packageNAME.Derived?
int x = 5; // How do I get 5?
最佳答案
您需要更深入地研究语法树以找到答案。在这种情况下,ASTView是一个很大的帮助。这是我与开普勒一起使用的更新站点:http://www.eclipse.org/jdt/ui/update-site
您的样本可以这样回答(简化):
/*
* Base b = new Derived(); // How do I get packageNAME.Derived?
*/
private String getClassNameFromConstructor(VariableDeclarationFragment fragment) {
Expression initializer = fragment.getInitializer();
if (initializer instanceof ClassInstanceCreation) {
ClassInstanceCreation instanceCreation = (ClassInstanceCreation)initializer;
if (instanceCreation.getType() instanceof SimpleType) {
SimpleType simpleType = (SimpleType)instanceCreation.getType();
return simpleType.getName().getFullyQualifiedName();
}
}
return null;
}
/*
* int x = 5; // How do I get 5?
*/
private String getInitialisationNumber(VariableDeclarationFragment fragment) {
Expression initializer = fragment.getInitializer();
if (initializer instanceof NumberLiteral) {
NumberLiteral numberLiteral = (NumberLiteral)initializer;
return numberLiteral.getToken();
}
return null;
}