Search code examples
javapluginsabstract-syntax-treeeclipse-jdt

How do I get the constructor of a variable?


I am trying to get the constructor of a variable by using an ASTVisitor.

public boolean visit(VariableDeclarationFragment node) 
{       
    IVariableBinding variableBinding = node.resolveBinding();

    // I can't seem to get the constructor here
}

SAMPLE

Base b = new Derived(); // How do I get packageNAME.Derived?
int x = 5; // How do I get 5?

Solution

  • You need to look deeper into the syntax tree to find the answers. The ASTView is a great help in cases like this. This is the update site I use with Kepler: http://www.eclipse.org/jdt/ui/update-site

    Your Samples could be answered like this (simplyfied):

    /*
     * 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;
    }