1 package org.opendaylight.controller.sal.binding.impl.util;
5 import java.util.concurrent.Callable;
6 import java.util.concurrent.locks.Lock;
8 import static com.google.common.base.Preconditions.*;
10 import java.lang.reflect.Constructor;
11 import java.lang.reflect.InvocationTargetException;
12 import java.util.ArrayList;
14 import com.google.common.base.Optional;
16 public class ClassLoaderUtils {
18 public static <V> V withClassLoader(ClassLoader cls,Callable<V> function) throws Exception {
19 return withClassLoaderAndLock(cls, Optional.<Lock>absent(), function);
22 public static <V> V withClassLoaderAndLock(ClassLoader cls,Lock lock,Callable<V> function) throws Exception {
23 checkNotNull(lock,"Lock should not be null");
24 return withClassLoaderAndLock(cls, Optional.of(lock), function);
27 public static <V> V withClassLoaderAndLock(ClassLoader cls,Optional<Lock> lock,Callable<V> function) throws Exception {
28 checkNotNull(cls, "Classloader should not be null");
29 checkNotNull(function,"Function should not be null");
30 if(lock.isPresent()) {
33 ClassLoader oldCls = Thread.currentThread().getContextClassLoader();
35 Thread.currentThread().setContextClassLoader(cls);
36 V result = function.call();
39 Thread.currentThread().setContextClassLoader(oldCls);
40 if(lock.isPresent()) {
46 public static Object construct(Constructor<? extends Object> constructor, ArrayList<Object> objects) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
47 Object[] initargs = objects.toArray(new Object[]{});
48 return constructor.newInstance(initargs);
52 public static Class<?> loadClassWithTCCL(String name) throws ClassNotFoundException {
53 if("byte[]".equals(name)) {
57 return Thread.currentThread().getContextClassLoader().loadClass(name);