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

Until java9 for adding external jar to classpath in runtime by programmatically everybody used:

URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();

Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});

method.invoke(sysloader, new Object[]{file.toURI().toURL()});

Now with java9 we have problem:

Exception in thread "main" java.lang.ClassCastException:

java.base/jdk.internal.loader.ClassLoaders$AppClassLoader

cannot be cast to java.base/java.net.URLClassLoader

URLClassLoader doesn't work anymore in Java 9. What to do now under jdk9 for adding an external jar to the classpath in runtime programmatically?

解决方案

The JavaSE9 release notes read about the same :

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

ClassLoader::getSytemClassLoader 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.

Additionally when an extended classpath is required, one can make use of

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

as suggested in this thread from Oracle. This comes with caveats:

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).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值