开发者

Add folder, which contains java sources, to classpath at runtime

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("uncompresse开发者_StackOverflowd" + 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());


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());
        }
    }
}


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.


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜