2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.sal.binding.generator.util;
10 import static com.google.common.base.Preconditions.checkNotNull;
12 import java.lang.reflect.Constructor;
13 import java.lang.reflect.InvocationTargetException;
14 import java.util.Arrays;
15 import java.util.List;
16 import java.util.concurrent.Callable;
17 import java.util.concurrent.locks.Lock;
19 import com.google.common.base.Joiner;
20 import com.google.common.base.Optional;
22 public final class ClassLoaderUtils {
24 private ClassLoaderUtils() {
25 throw new UnsupportedOperationException("Utility class");
28 public static <V> V withClassLoader(ClassLoader cls, Callable<V> function) throws Exception {
29 return withClassLoaderAndLock(cls, Optional.<Lock> absent(), function);
32 public static <V> V withClassLoaderAndLock(ClassLoader cls, Lock lock, Callable<V> function) throws Exception {
33 checkNotNull(lock, "Lock should not be null");
34 return withClassLoaderAndLock(cls, Optional.of(lock), function);
37 public static <V> V withClassLoaderAndLock(ClassLoader cls, Optional<Lock> lock, Callable<V> function)
39 checkNotNull(cls, "Classloader should not be null");
40 checkNotNull(function, "Function should not be null");
41 if (lock.isPresent()) {
44 ClassLoader oldCls = Thread.currentThread().getContextClassLoader();
46 Thread.currentThread().setContextClassLoader(cls);
47 return function.call();
49 Thread.currentThread().setContextClassLoader(oldCls);
50 if (lock.isPresent()) {
56 public static Object construct(Constructor<? extends Object> constructor, List<Object> objects)
57 throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
58 Object[] initargs = objects.toArray(new Object[] {});
59 return constructor.newInstance(initargs);
62 public static Class<?> loadClassWithTCCL(String name) throws ClassNotFoundException {
63 if ("byte[]".equals(name)) {
65 } else if("char[]".equals(name)) {
69 return Thread.currentThread().getContextClassLoader().loadClass(name);
70 } catch (ClassNotFoundException e) {
71 String[] components = name.split("\\.");
72 String potentialOuter;
73 int length = components.length;
74 if (length > 2 && (potentialOuter = components[length - 2]) != null && Character.isUpperCase(potentialOuter.charAt(0))) {
76 String outerName = Joiner.on(".").join(Arrays.asList(components).subList(0, length - 1));
77 String innerName = outerName + "$" + components[length-1];
78 return Thread.currentThread().getContextClassLoader().loadClass(innerName);
85 public static Class<?> tryToLoadClassWithTCCL(String fullyQualifiedName) {
87 return loadClassWithTCCL(fullyQualifiedName);
88 } catch (ClassNotFoundException e) {