编程语言
首页 > 编程语言> > 在java 9下运行时将jar添加到类路径

在java 9下运行时将jar添加到类路径

作者:互联网

直到用于通过编程方式将所有人使用的外部jar添加到运行时的类路径:

URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
method.invoke(sysloader, new Object[]{file.toURI().toURL()});

现在用java9我们有问题:

Exception in thread “main” java.lang.ClassCastException:
java.base/jdk.internal.loader.ClassLoaders$AppClassLoader
cannot be cast to java.base/java.net.URLClassLoader

URLClassLoader在Java 9中不再起作用.现在在jdk9下如何以编程方式在运行时向类路径添加外部jar?

解决方法:

JavaSE9 release notes读到了同样的内容:

The application class loader is no longer an instance of
java.net.URLClassLoader (an implementation detail that was never
specified in previous releases).

Code that assumes that
07001 returns a URLClassLoader object will
need to be updated.

Note that Java SE and the JDK do not provide an
API for applications or libraries to dynamically augment the class
path at run-time
.

另外,当需要扩展类路径时,可以使用

Class<?> clazz = Class.forName("nameofclass", true, new URLClassLoader(urlarrayofextrajarsordirs));

正如本thread from Oracle所述.这有一些警告:

  • java.util.ServiceLoader uses the thread’s ClassLoader context Thread.currentThread().setContextClassLoader(specialloader);

  • java.sql.DriverManager does honors the calling class’ ClassLoader, -not- the Thread’s ClassLoader. Create Driver directly
    using Class.forName("drivername", true, new
    URLClassLoader(urlarrayofextrajarsordirs).newInstance();

  • javax.activation uses the thread’s ClassLoader context (important for javax.mail).

标签:java,jar,classpath,java-9,urlclassloader,java9
来源: https://codeday.me/bug/20190923/1813804.html