How can I mimic fully compatible ICompilationUnit from standalone Java files?

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

问题


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 File.

Upon suggestion in another post, I am manually creating an IJavaElement from any Java file:

IJavaElement element = JavaCore.create(file);

This seems to work fine, except for some specific cases. E.g., when I try to get the source of the file I get the exception JavaModelException:

ICompilationUnit compUnit = (ICompilationUnit)element;
compUnit.getSource();

Exception message:

Java Model Exception: Java Model Status [test does not exist]
at org.eclipse.jdt.internal.core.JavaElement.newJavaModelException(JavaElement.java:566)
at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:247)
at org.eclipse.jdt.internal.core.Openable.openAncestors(Openable.java:505)
at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:241)
at org.eclipse.jdt.internal.core.Openable.openAncestors(Openable.java:505)
at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:241)
at org.eclipse.jdt.internal.core.Openable.openAncestors(Openable.java:505)
at org.eclipse.jdt.internal.core.CompilationUnit.openAncestors(CompilationUnit.java:1176)
at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:241)
at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:579)
at org.eclipse.jdt.internal.core.JavaElement.getElementInfo(JavaElement.java:316)
at org.eclipse.jdt.internal.core.JavaElement.getElementInfo(JavaElement.java:302)
at org.eclipse.jdt.internal.core.Openable.getBuffer(Openable.java:285)
at org.eclipse.jdt.internal.core.CompilationUnit.getSource(CompilationUnit.java:903)
at org.autorefactor.refactoring.rules.RefactoringContext.getSource(RefactoringContext.java:126)
... 19 more

I'm afraid the same will happen with other methods. How can I have a fully working ICompilationUnit/IJavaElement?

Edit: I've figured that if the source file is open in the editor, I won't get this exception. Still, how to avoid it?

来源:https://stackoverflow.com/questions/41100699/how-can-i-mimic-fully-compatible-icompilationunit-from-standalone-java-files

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