I'm writing an Eclipse plugin. I'm looking for the right way to get a selected java file and find it's corresponding .class file.
The way I'm doing it now works for a standard Eclipse java project, but seems less than elegant: I call IJavaProject#getOutputLocation and combine that with the path to the selected file. Then I just change .java to .class.
Here's the code for the method that translates from the incoming selection to a path:
def selection_to_path selection path = selection.get_paths.first output_locatio开发者_如何转开发n = path.get_first_segment.get_output_location root = org.eclipse.core.resources::ResourcesPlugin.getWorkspace().get_root folder = root.get_folder output_location folder.get_location.to_s path_to_file_as_string = path.get_last_segment.get_path.to_s path_to_file_as_string[/\.java$/] = ".class" path_elements_of_java_file = path_to_file_as_string.split("/")[3..-1] all_elements = folder.get_location.to_s.split("/") + path_elements_of_java_file File.join(all_elements) end
This works, but I suspect it fails often enough that it's not the right thing to do. In particular, the documentation for getOutputLocation says that my assumptions about class file locations are too simplistic.
So what's the right way to do this?
I don't need this to work all of the time. Certainly there will be many cases where a .java file doesn't have a corresponding .class file (compilation errors, no automatic builds, whatever). I don't care about those; I just want to know if there is a class file, what is its full path?
There is no method, which directly finds the corresponding class file resource. The proper way to get the corresponding output folder is to:
- Convert the selection to
IJavaElement
, most probablyICompilationUnit
(.java files) - Find the corresponding
IPackageFragmentRoot
(the source folder) - Find the resolved
IClasspathEntry
- Find the output location using
IClasspathEntry.getOutputLocation()
or theIJavaProject.getOutputLocation()
method, depending on whether the classpath entry has separate output location. - Construct the path to the classpath based on the
ICompilationUnit
's package
The class file may or may not exist depending on whether the project has been build, whether there are build path errors, etc. So, there are additional heuristics, which you need to use to determine whether the result of the above algorithm will be usable.
精彩评论