Java 9, compatability issue with ClassLoader.getSystemClassLoader

后端 未结 8 1292
面向向阳花
面向向阳花 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:01

    Shadov pointed to a thread at the oracle community. There is the correct answer:

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

    The caveats mentioned there are also important:

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

提交回复
热议问题