Question

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?
Was it helpful?

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

OTHER TIPS

Variables don't have constructors. Objects have constructors. Find the assignment, find the expression being assigned, and if that expression is a constructor you can get the class name from that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top