mardi 28 mars 2023

java 17 - reflection to use methods in external jar files - Unable to make protected void java.net.URLClassLoader.addURL(java.net.URL) accessible

I've this code below which is used to load methods defined in some external jar files and in the web application using Spring Boot 2.7.10 version, it can invoke these external methods at run time.

This works fine with java 11, but when upgraded to java 17, it has error:

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);
        }
    }

Does anyone know how this code can work with java 17 or if it can change to use something else which can work with both java 11 and java 17? Thanks.

NOTE:

  • Adding arguments to JDK is not an option as I cannot change that in servlet container Tomcat or JRE of development machine.
  • Downgrade java version to 11 is also not an option.




Aucun commentaire:

Enregistrer un commentaire