我下面的这段代码用于加载一些外部
jar
文件中定义的方法,在使用Spring Boot 2.7.10版本的Web应用程序中,它可以在运行时调用这些外部方法。
这在 java 11 上工作正常,但是当升级到 java 17 时,它有错误:
Caused by: java.lang.reflect.InaccessibleObjectException: Unable to make protected void java.net.URLClassLoader.addURL(java.net.URL) accessible: module java.base does not "opens java.net" to unnamed module @221af3c0
private static void addToClassPath(String jarFilePath) {
try {
File file = new File(jarFilePath);
if (!(file.exists() && file.canRead())) {
throw new UdfDirectoryNotAccessibleException(jarFilePath);
}
URL url = file.toURI().toURL();
URLClassLoader urlClassLoader = (URLClassLoader) UdfInvoker.class.getClassLoader();
Class urlClass = URLClassLoader.class;
Method method = urlClass.getDeclaredMethod("addURL", new Class[]{URL.class});
// error here since java 17
method.setAccessible(true);
method.invoke(urlClassLoader, new Object[] { url });
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
throw new UdfFailedLoadingException(jarFilePath, ex.getMessage(), ex);
} catch (MalformedURLException ex) {
throw new UdfJarFileNotAccessibleException(jarFilePath, ex.getMessage(), ex);
}
}
有谁知道这段代码如何与 java 17 一起工作,或者它是否可以更改为使用其他可以同时与 java 11 和 java 17 一起工作的代码?谢谢。
注意: