System.getProperty(“java.class.path”)不显示“WEB-INF / lib”和包括瓶子 [英] System.getProperty("java.class.path") does not show "WEB-INF/lib" and the including jars

查看:1020
本文介绍了System.getProperty(“java.class.path”)不显示“WEB-INF / lib”和包括瓶子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String CompilePath = "abc.java";
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
String classpath = System.getProperty("java.class.path");
System.setProperty("java.class.path", classpath + ";" + LocalMachine.home + "WebContent/WEB-INF/lib");
int result = compiler.run(null, null, null, CompilePath);

当执行JUnit测试时,上述运行良好,因为所有 jars 需要用于编译 abc.java 文件。但是当同一代码作为服务器运行时,它无法找到所需的 jar 文件。 System.getProperty(java.class.path)的输出是
E:\apache-tomcat-7.0.4 \bin\bootstrap.jar; E:\apache-tomcat-7.0.4\bin\tomcat-juli.jar; C:\Program Files\Java\jdk1.6.0_21\lib\\ \\ tools.jar

The above runs fine when executed as a JUnit test since all the jars required for compiling the abc.java file. But when the same code is being run in as server, it fails to find the required jar files. The output of System.getProperty("java.class.path") is E:\apache-tomcat-7.0.4\bin\bootstrap.jar;E:\apache-tomcat-7.0.4\bin\tomcat-juli.jar;C:\Program Files\Java\jdk1.6.0_21\lib\tools.jar

所以,我的问题是如何让编译器引用来自WEB-INF / lib目录的jar文件?

So, my question is how do I make the compiler refer to the jar files from the WEB-INF/lib directory?

推荐答案

他们设置java.class.path系统属性的方式是要求麻烦 - 最好不要这样做。 更优雅的方法是使用 -classpath 选项传递自定义类路径。请参阅如何使用JDK6 ToolProvider和JavaCompiler与上下文类加载器?

They way you are setting the java.class.path system property is asking for trouble - better not do that. More elegant approach would be to use the -classpath option to pass in the custom classpath. See How do I use JDK6 ToolProvider and JavaCompiler with the context classloader? for details.

此问题也可以作为参考:使用自定义类加载器中的javax.tools.ToolProvider?

Also this question can be useful reference: Using javax.tools.ToolProvider from a custom classloader?

至于构建实际的类路径,您可以将上下文类加载器转换为 URLClassLoader ,并从这些URL获取文件此答案)。

As to building the actual classpath, you could cast the context classloader to URLClassLoader and get files from those URLs (as done in this answer).

或者您可以使用 ServletContext getRealPath(String)手动构建整个类路径

ServletConfig cfg = ...; //obtained in Servlet.init(ServletConfig) method
ServletContex ctx = cfg.getServletContext();
String realWebInfPath = ctx.getRealPath("WEB-INF/lib");
//TODO use the realWebInfPath to create a File object and iterate over all JAR files

警告:如果网络应用程序已展开(不是WAR文件),两种方法只有有效。如果它没有扩展,你是运气不好。

Warning: both approaches ONLY work if web application is expanded (not WAR file). If it is not expanded, you are out of luck.

这篇关于System.getProperty(“java.class.path”)不显示“WEB-INF / lib”和包括瓶子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆