views:

164

answers:

3

Is it possible to add a folder which contains java source code as a classpath element. I have tried a few things and it seems that the classloadr is not picking up java soruce files? One of my attempts is shown below....

File uncompressedSrc = new File("uncompressed" + File.separator + "src" + File.separator);
URL uncompressedSrcURL = null;
try {
    uncompressedSrcURL = new URL("file://"
        + uncompressedSrc.getAbsolutePath());
} catch (MalformedURLException e) {
    e.printStackTrace();
}
URL elements[] = { uncompressedSrcURL };
new URLClassLoader(elements, ClassLoader.getSystemClassLoader());
+1  A: 

Sorry. I skimmed through your question way to fast.

As @Daniel says, the JVM can not read .java files, only .class files.

The java-files can be compiled into class-files and loaded in the JVM programatically as described here: Programmatically Compile and Execute with Java

The key ingredient is the following

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager filemanager = compiler.getStandardFileManager( null, null, null );

try {
    Iterable compilationUnits = filemanager.getJavaFileObjects( file );
    compiler.getTask( null, filemanager, null, null, null, compilationUnits ).call();

    filemanager.close();
} catch ( IOException e ) {
    e.printStackTrace();
}

Hope that helps!

aioobe
Ok, but what about the fact that if I add a folder as a java -cp parameter it is scanned even for .java files. If I use URLClassloader it seems to be skipping java files...
markovuksanovic
Hmm.. I doubt you'll get that working. Unless you dig out the class-path and scan it yourself programatically, I think the java-files in the class-path will be ignored by the JVM.
aioobe
+1  A: 

Java source code is nothing the JVM can handle by itself. Only compiled class files may be loaded by the classloader. So you may only add the content of JAR files or CLASS files to the classpath.

Daniel Bleisteiner
A: 

I have found a solution to my problem... I used the following dirty "hack" to add a folder to class path...

public static void addUrl(URL u) {
    URLClassLoader sysloader = (URLClassLoader) ClassLoader
            .getSystemClassLoader();
    Class<URLClassLoader> sysclass = URLClassLoader.class;

    try {
        Method method = sysclass.getDeclaredMethod("addURL", parameters);
        method.setAccessible(true);
        method.invoke(sysloader, new Object[] { u });
    } catch (Throwable t) {
        t.printStackTrace();
        try {
            throw new IOException(
                    "Error, could not add URL to system classloader");
        } catch (IOException e) {
            logger.log(Level.SEVERE, e.getMessage());
        }
    }
}
markovuksanovic
I also added a gist, for people using github, to clone.. And, hopefully, easily solve the same problem...git://gist.github.com/387972.git
markovuksanovic