Get ICompilationUnit/ITypeRoot from standalone java file for Eclipse Plugin

左心房为你撑大大i 提交于 2019-12-11 06:25:45

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/41066054/get-icompilationunit-ityperoot-from-standalone-java-file-for-eclipse-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!