我如何获得变量的构造函数?

时间:2014-02-23 20:55:56

标签: java plugins abstract-syntax-tree eclipse-jdt

我试图通过使用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?

2 个答案:

答案 0 :(得分:1)

变量没有构造函数。对象有构造函数。找到赋值,找到被赋值的表达式,如果该表达式是构造函数,则可以从中获取类名。

答案 1 :(得分:1)

您需要深入了解语法树以找到答案。在这样的情况下,ASTView是一个很好的帮助。这是我与Kepler一起使用的更新站点: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;
}