System.getProperty(“java.class.path”) does not show “WEB-INF/lib” and the including jars

后端 未结 4 1263
迷失自我
迷失自我 2021-01-07 06:45
String CompilePath = \"abc.java\";
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
String classpath = System.getProperty(\"java.class.path\");
System.s         


        
4条回答
  •  太阳男子
    2021-01-07 07:44

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

    Provide that the webapp's WAR is expanded, you should be able to programmatically create a classpath string that corresponds to what the web container gives you. It is "simply" a matter of duplicating the effective class search path that the web container uses.

    However, I suspect that passing a "classpath" argument to the compiler, explicitly or via the System properties is the wrong approach. I found the following in this IBM article.

    Compiling Java source requires the following components:

    • A classpath, from which the compiler can resolve library classes. The compiler classpath is typically composed of an ordered list of file system directories and archive files (JAR or ZIP files) that contain previously compiled .class files. The classpath is implemented by a JavaFileManager that manages multiple source and class JavaFileObject instances and the ClassLoader passed to the JavaFileManager constructor. ...

    So it would seem that the correct approach is to just grab the relevant classloader object and pass it to the JavaFileManager constructor.

提交回复
热议问题