Improve ClassLoaderUtils.loadClassWithTCCL()
[yangtools.git] / common / util / src / main / java / org / opendaylight / yangtools / util / ClassLoaderUtils.java
index 45f4e0ce49dc92a29862a4dee18773c6c1ed1c62..b5064080ad93757a026209fdabcb17005af71da9 100644 (file)
@@ -8,6 +8,7 @@
 package org.opendaylight.yangtools.util;
 
 import static com.google.common.base.Preconditions.checkNotNull;
+
 import com.google.common.base.Joiner;
 import com.google.common.base.Preconditions;
 import com.google.common.base.Splitter;
@@ -109,9 +110,9 @@ public final class ClassLoaderUtils {
                 final String outerName = Joiner.on(".").join(components.subList(0, length));
                 final String innerName = outerName + "$" + components.get(length);
                 return cls.loadClass(innerName);
-            } else {
-                throw e;
             }
+
+            throw e;
         }
     }
 
@@ -129,14 +130,28 @@ public final class ClassLoaderUtils {
     }
 
     public static Class<?> loadClassWithTCCL(final String name) throws ClassNotFoundException {
-        return loadClass(Thread.currentThread().getContextClassLoader(), name);
+        final Thread thread = Thread.currentThread();
+        final ClassLoader tccl = thread.getContextClassLoader();
+        if (tccl == null) {
+            throw new ClassNotFoundException("Thread " + thread + " does not have a Context Class Loader, cannot load "
+                    + name);
+        }
+        return loadClass(tccl, name);
     }
 
-    public static Class<?> tryToLoadClassWithTCCL(final String fullyQualifiedName) {
+    public static Class<?> tryToLoadClassWithTCCL(final String fullyQualifiedClassName) {
+        final Thread thread = Thread.currentThread();
+        final ClassLoader tccl = thread.getContextClassLoader();
+        if (tccl == null) {
+            LOG.debug("Thread {} does not have a Context Class Loader, not loading class {}", thread,
+                fullyQualifiedClassName);
+            return null;
+        }
+
         try {
-            return loadClassWithTCCL(fullyQualifiedName);
+            return loadClass(tccl, fullyQualifiedClassName);
         } catch (final ClassNotFoundException e) {
-            LOG.debug("Failed to load class {}", fullyQualifiedName, e);
+            LOG.debug("Failed to load class {}", fullyQualifiedClassName, e);
             return null;
         }
     }