繁体   English   中英

在运行时将包含Java源代码的文件夹添加到类路径

[英]Add folder, which contains java sources, to classpath at runtime

是否可以添加一个包含Java源代码的文件夹作为classpath元素。 我已经尝试了一些方法,看来classloadr没有拾取Java soruce文件? 我的尝试之一如下所示。

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

我找到了解决问题的方法...我使用以下肮脏的“ hack”将文件夹添加到类路径中...

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

抱歉。 我快速浏览了您的提问方式。

正如@Daniel所说,JVM无法读取.java文件,只能读取.class文件。

可以将Java文件编译为类文件,并按如下所述以编程方式加载到JVM中:以编程方式使用Java编译和执行

关键成分如下

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

希望有帮助!

Java源代码是JVM本身无法处理的任何内容。 类加载器只能加载已编译的类文件。 因此,您只能将JAR文件或CLASS文件的内容添加到类路径中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM