Getting the .java from the package name

352 views Asked by At

I'm using QDox to parse java sources. I have a problem with this interface:

import test.Word;

public interface Spellable {
    /**
    * Checks the spell of the word in a given language
    */
    public boolean checkSpell (Word word);  
}

At the moment of parsing the Word type I need to know where the path in the filesystem is. So, is there any way to know that?, maybe using the classpath?

1

There are 1 answers

2
Andrzej Doyle On

I don't think it's possible to do this in a nice, 100%-definitely-compatible way. Java actually tries to abstract you away from the filesystem a little bit through the classpath mechanism.

Nevertheless, you can usually get the file path via the classloader. First step is to get a reference to a classloader that can find whatever resource you're interested in (usually the classloader for any of your own classes will work fine; if you have a more complex scenario you should hopefully know which classloader to use).

Then you can ask the classloader for the location of a given resource as a URL, for example:

final ClassLoader loader = getClass().getClassLoader();
final URL resourceLocation = loader.getResource("com/mycomp/coolapp/checkthis.doc");

Now if you're lucky, the URL will use the file:/ protocol, and will describe a location on your local filesystem. If so, you can extract this path and use it as the filesystem location of whatever classpath resource you just looked up. If it's not a file:/ resource, the class may not even exist on your local machine (e.g. it's being loaded remotely via RMI) so you're out of luck in any case.

If this sounds complicated - perhaps you can pass in the working directory as a system property from your Java startup script (e.g. java ... -Dworking.dir=$(pwd)).