问题
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