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.ArrayList;
11 import java.util.List;
13 import com.google.common.base.Optional;
15 public final class ClassLoaderUtils {
17 private ClassLoaderUtils() {
18 throw new UnsupportedOperationException("Utility class");
21 public static <V> V withClassLoader(ClassLoader cls, Callable<V> function) throws Exception {
22 return withClassLoaderAndLock(cls, Optional.<Lock> absent(), function);
25 public static <V> V withClassLoaderAndLock(ClassLoader cls, Lock lock, Callable<V> function) throws Exception {
26 checkNotNull(lock, "Lock should not be null");
27 return withClassLoaderAndLock(cls, Optional.of(lock), function);
30 public static <V> V withClassLoaderAndLock(ClassLoader cls, Optional<Lock> lock, Callable<V> function)
32 checkNotNull(cls, "Classloader should not be null");
33 checkNotNull(function, "Function should not be null");
34 if (lock.isPresent()) {
37 ClassLoader oldCls = Thread.currentThread().getContextClassLoader();
39 Thread.currentThread().setContextClassLoader(cls);
40 return function.call();
42 Thread.currentThread().setContextClassLoader(oldCls);
43 if (lock.isPresent()) {
49 public static Object construct(Constructor<? extends Object> constructor, List<Object> objects)
50 throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
51 Object[] initargs = objects.toArray(new Object[] {});
52 return constructor.newInstance(initargs);
55 public static Class<?> loadClassWithTCCL(String name) throws ClassNotFoundException {
56 if ("byte[]".equals(name)) {
60 return Thread.currentThread().getContextClassLoader().loadClass(name);
63 public static Class<?> tryToLoadClassWithTCCL(String fullyQualifiedName) {
65 return loadClassWithTCCL(fullyQualifiedName);
66 } catch (ClassNotFoundException e) {