Excluding certain classes from a thread's context classloader in Java?
If I have a program invoked in the following way
java -cp a.jar;b.jar;c.jar MainClass
All the classes from a.jar, b.jar, and c.jar will be available to all the threads in my program. I'd like to have a thread that is created at some point during my program run with a limited set of classes available, excluding most of the classes in a.jar, b.jar, and c.jar. Is there a way to do this either by adding the required classes to a classloader that doesn't contain everything from the system classpath, or taking a classloader and removing a bunch of classes from i开发者_开发百科t? The only option I currently know of is to write a bootstrap class and load the required classpath for each thread at JVM Initialization. Am I missing something obvious or is bootstrapping my only option?
You could write a custom ClassLoader (ie extending URLClassLoader) which throws ClassNotFound exceptions in loadClass(String name) for the classes you do not want on the path. Set this as the contextClassLoader and load the Runnable of the thread from it.
精彩评论