How can I safely solve this Java context classloader problem?

南楼画角 提交于 2019-12-03 07:22:56
McDowell
Thread.currentThread().getContextClassLoader()

If the code in JEditorPane.registerEditorKitForContentType does not check for a null return value in the above code, this is a bug in JEditorPane. Note that MyClass.class.getClassLoader() may also return null. The only one you can rely on is the system ClassLoader.

The pattern for setting the context ClassLoader for an invocation usually looks something like this:

Thread thread = Thread.currentThread();
ClassLoader old = thread.getContextClassLoader();
thread.setContextClassLoader(fooClassLoader);
try {
  // do call that depends on context ClassLoader
} finally {
  thread.setContextClassLoader(old);
}

The value that should be set via setContextClassLoader will depend on the intent of the code that is consuming it and the design of the ClassLoader framework you are running in.

In a stand-alone application, you can probably get away with just using this ClassLoader (passing in a ref to the current class):

private ClassLoader findClassLoaderForContext(Class<?> c) {
  ClassLoader context = Thread.currentThread().getContextClassLoader();
  ClassLoader me = c.getClassLoader();
  ClassLoader system = ClassLoader.getSystemClassLoader();
  return (context == null) ? (me == null) ? system : me : context;
}

In a ClassLoader-sensitive plug-in framework (a Java EE server would be a prime example), it would pay to understand the nature and usage of the loading scheme.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!