Class TemporaryClassLoaderContext

  • All Implemented Interfaces:
    AutoCloseable

    @Public
    public final class TemporaryClassLoaderContext
    extends Object
    implements AutoCloseable
    Sets a context class loader in a "try-with-resources" pattern.
    
     try (TemporaryClassLoaderContext ignored = TemporaryClassLoaderContext.of(classloader)) {
         // code that needs the context class loader
     }
     

    This is conceptually the same as the code below.

    
     ClassLoader original = Thread.currentThread().getContextClassLoader();
     Thread.currentThread().setContextClassLoader(classloader);
     try {
         // code that needs the context class loader
     } finally {
         Thread.currentThread().setContextClassLoader(original);
     }
     
    • Method Detail

      • of

        public static TemporaryClassLoaderContext of​(ClassLoader cl)
        Sets the context class loader to the given ClassLoader and returns a resource that sets it back to the current context ClassLoader when the resource is closed.
        
         try (TemporaryClassLoaderContext ignored = TemporaryClassLoaderContext.of(classloader)) {
             // code that needs the context class loader
         }