Search code examples
javaeclipse-jdt

jdt: Check if IField is an reference type


I'm using the jdt java model to get information about my existing projects in the workspace.

With the getFields() method of IType I get all fields of a particular class.

But I need to know if a particular field is a reference type or not. Furthermore I also need to know if the reference type contains a specific method.

Example:

class A {

   List list<String>
   int a;
}

So I want to know if the field "list" of the Class A is a reference type and if "list" contains the e.g. method "remove".

How can I do this?


Solution

  • You will need to go deeper into the Java Model using the abstract syntax tree (AST). The following code has not been tested, but it should give you a good idea on how to get going.

    Step 1) Parse the ICompilationUnit that includes the field into an ASTNode.

        ASTParser parser = ASTParser.newParser(AST.JLS4);
        parser.setResolveBindings(true);
        parser.setSource(field.getCompilationUnit());
        ASTNode unitNode = parser.createAST(new NullProgressMonitor());
    

    Step 2) Find the IField in the ASTNode using the visitor pattern

        unitNode.accept(new ASTVisitor() {
            @Override
            public boolean visit(VariableDeclarationFragment node) {
                IJavaElement element = node.resolveBinding().getJavaElement();
                if (field.equals(element)) {
                    FieldDeclaration fieldDeclaration = (FieldDeclaration)node.getParent();
                    IType fieldType = (IType)fieldDeclaration.getType().resolveBinding().getJavaElement();
                }
                return false;
            }
        });
    

    From the FieldDeclaration you can get the IType of the field. Guessing from your question, you know how to proceed from here (i.e. with fieldType.getMethods()).

    A good tool to work with the AST is the ASTView from the JDT UI Tools (Update Site: http://www.eclipse.org/jdt/ui/update-site). Using this tool you can have a look at the code and see how the AST model is structured.