Java 9, compatability issue with ClassLoader.getSystemClassLoader

后端 未结 8 1321
面向向阳花
面向向阳花 2020-11-29 09:19

The following code adds jar file to the build path, it works fine with Java 8. However, it throws exception with Java 9, the exception is related to the cast to URLClassLoad

8条回答
  •  醉酒成梦
    2020-11-29 10:02

    I was given a spring boot application that runs in Java 8. I had the task to upgrade it to Java 11 version.

    Issue faced:

    Caused by: java.lang.ClassCastException: jdk.internal.loader.ClassLoaders$AppClassLoader (in module: java.base) cannot be cast to java.net.URLClassLoader (in module: java.base)

    Way around used:

    Create a class:

    import java.net.URL;
    
    /**
     * This class has been created to make the code compatible after migration to Java 11
     * From the JDK 9 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 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."
     */
    
    public class ClassLoaderConfig {
    
        private final MockClassLoader classLoader;
    
        ClassLoaderConfig() {
            this.classLoader = new MockClassLoader(new URL[0], this.getClass().getClassLoader());
        }
    
        public MockClassLoader getClassLoader() {
            return this.classLoader;
        }
    }
    

    Create Another class:

    import java.net.URL;
    import java.net.URLClassLoader;
    
    public class MockClassLoader extends URLClassLoader {
    
        public MockClassLoader(URL[] urls, ClassLoader parent) {
            super(urls, parent);
        }
    
        public void addURL(URL url) {
            super.addURL(url);
        }
    }
    

    Now set it in the current thread from your main class (Right at the beginning of your application)

    Thread.currentThread().setContextClassLoader(new ClassLoaderConfig().getClassLoader());
    

    Hope this solution works for your!!!

提交回复
热议问题