We have answer of your question!

100% solved queries, no empty question

Question: Get ICompilationUnit/ITypeRoot from standalone java file for Eclipse Plugin


I am hacking an Eclipse Plugin that is working perfectly for Java files in Java projects. I want to make it work for Java files in any kind of project.

This plugin processes each Java file as a ICompilationUnit. However, in my approach I can only get an instance of IFile.

How can I create a ICompilationUnit from this IFile object?

As alternative a ITypeRoot might also work. I've seen this being created directly from the editor using the following:

IJavaElement input= JavaUI.getEditorInputJavaElement(editorInput);
        if (input instanceof ITypeRoot) {
            return (ITypeRoot) input;

This approach works even with non Java projects (java files from generic projects/directories that are opened in the editor), which makes me believe that something similar can be achieved for files directly.

Question author Luis-cruz | Source



JavaCore.create(IFile) will return an ICompilationUnit if that is appropriate for the file:

IFile file = ...

IJavaElement element = JavaCore.create(file); 

if (element instanceof ICompilationUnit) {
  ICompilationUnit compUnit = (ICompilationUnit)element;


Other objects may be returned, for example IClassFile for a .class file.

Answer author Greg-449

Tickanswer.com is providing the only single recommended solution of the question Get ICompilationUnit/ITypeRoot from standalone java file for Eclipse Plugin under the categories i.e java , eclipse , eclipse-plugin , eclipse-jdt , . Our team of experts filter the best solution for you.

Related Search Queries:

You may also add your answer

Thanks for contributing an answer to Tick Answer!