Try with resource Context Classloaders
Join the DZone community and get the full member experience.
Join For Freepublic void doSomething() { ClassLoader context = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(Example.class.getClassLoader()); // Class class that required the context class loader Endpoint.publish(null, null); } finally { Thread.currentThread().setContextClassLoader(context); } }
public void doSomething() { try (CloseableContext c = contextClassLoader(Example.class)) { // Class class that required the context class loader Endpoint.publish(null, null); } }
public void doSomething() { try (contextClassLoader(Example.class)) { // Compilation errors // Class class that required the context class loader Endpoint.publish(null, null); } }
public static CloseableContext contextClassLoader(Class loader) { return contextClassLoader(loader.getClassLoader()); } public static CloseableContext contextClassLoader(ClassLoader loader) { final Thread currentThread = Thread.currentThread(); final ClassLoader ocl = currentThread.getContextClassLoader(); currentThread.setContextClassLoader(loader); return new CloseableContext(currentThread, ocl); } public static class CloseableContext implements AutoCloseable { private Thread _currentThread; private ClassLoader _ocl; private CloseableContext(Thread currentThread, ClassLoader ocl) { this._currentThread = currentThread; this._ocl = ocl; } @Override public void close() { this._currentThread.setContextClassLoader(this._ocl); } }
Published at DZone with permission of Gerard Davison, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments