1 package org.opendaylight.controller.sal.binding.impl.util;
3 import java.util.concurrent.Callable;
4 import java.util.concurrent.locks.Lock;
6 import static com.google.common.base.Preconditions.*;
8 import java.lang.reflect.Constructor;
9 import java.lang.reflect.InvocationTargetException;
10 import java.util.Arrays;
11 import java.util.List;
13 import com.google.common.base.Joiner;
14 import com.google.common.base.Optional;
16 public final class ClassLoaderUtils {
18 private ClassLoaderUtils() {
19 throw new UnsupportedOperationException("Utility class");
22 public static <V> V withClassLoader(ClassLoader cls, Callable<V> function) throws Exception {
23 return withClassLoaderAndLock(cls, Optional.<Lock> absent(), function);
26 public static <V> V withClassLoaderAndLock(ClassLoader cls, Lock lock, Callable<V> function) throws Exception {
27 checkNotNull(lock, "Lock should not be null");
28 return withClassLoaderAndLock(cls, Optional.of(lock), function);
31 public static <V> V withClassLoaderAndLock(ClassLoader cls, Optional<Lock> lock, Callable<V> function)
33 checkNotNull(cls, "Classloader should not be null");
34 checkNotNull(function, "Function should not be null");
35 if (lock.isPresent()) {
38 ClassLoader oldCls = Thread.currentThread().getContextClassLoader();
40 Thread.currentThread().setContextClassLoader(cls);
41 return function.call();
43 Thread.currentThread().setContextClassLoader(oldCls);
44 if (lock.isPresent()) {
50 public static Object construct(Constructor<? extends Object> constructor, List<Object> objects)
51 throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
52 Object[] initargs = objects.toArray(new Object[] {});
53 return constructor.newInstance(initargs);
56 public static Class<?> loadClassWithTCCL(String name) throws ClassNotFoundException {
57 if ("byte[]".equals(name)) {
61 return Thread.currentThread().getContextClassLoader().loadClass(name);
62 } catch (ClassNotFoundException e) {
63 String[] components = name.split("\\.");
64 String potentialOuter;
65 int length = components.length;
66 if (length > 2 && (potentialOuter = components[length - 2]) != null && Character.isUpperCase(potentialOuter.charAt(0))) {
68 String outerName = Joiner.on(".").join(Arrays.asList(components).subList(0, length - 1));
69 String innerName = outerName + "$" + components[length-1];
70 return Thread.currentThread().getContextClassLoader().loadClass(innerName);
77 public static Class<?> tryToLoadClassWithTCCL(String fullyQualifiedName) {
79 return loadClassWithTCCL(fullyQualifiedName);
80 } catch (ClassNotFoundException e) {