java 17 - 反射使用外部 jar 文件中的方法 - 无法使 protected void java.net.URLClassLoader.addURL(java.net.URL) 可访问

问题描述 投票:0回答:0

我下面的这段代码用于加载一些外部

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 一起工作的代码?谢谢。

注意:

  • 向 JDK 添加参数不是一个选项,因为我无法在开发机器的 servlet 容器 Tomcat 或 JRE 中更改它。
  • 将 java 版本降级到 11 也不是一个选项。
java reflection java-11 java-17
© www.soinside.com 2019 - 2024. All rights reserved.