Search code examples
eclipseeclipse-plugineclipse-jdt

eclipse plugin : How to create org.eclipse.jdt.core.IType from the datatype of org.eclipse.jdt.core.dom.FieldDeclaration?


Using ASTParser I am parsing a class. Now my goal is to modify the class of one of the field.The field is available as FieldDeclaration now I want to create IType from the data type of FieldDeclaration.

example: class Dog{ private Collar c; }

Here "private Collar c" is already available as FieldDeclaration .How is it possible to create IType of "Collar"?

Thanks in advance


Solution

  • There are several steps that you need to follow here. I am going to sketch out the solution. But, I'll leave it up to you to figure out the final code to write.

    The first thing to realize is that the IType classes and the FieldDeclaration classes are created in different ways and are used to do different things. IType and related interfaces are used to look at the structure of an entire program. Whereas FieldDeclartion and related classes are part of the Java DOM and used to look at the structure of a single file. If the class you are working with is not inside of a proper Java project in Eclipse, then there will be no IType to create.

    So, here is what you do:

    1. ASTParser parser = ASTParser.create(AST.JLS8);
    2. parser.setResolveBindings(true);
    3. CompilationUnit unit = parser.parse(...);
    4. get your fieldDeclaration
    5. String name = fieldDeclaration.getType().resolveBinding().getQualifiedName();
    6. IJavaProject project = JavaCore.create(IProject); // pass in the resource correspoding to the project in which this is based
    7. IType type = project.findType(name);

    Not easy, but following these steps should work. I can provide clarification on steps if you need them.