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.util;
10 import static com.google.common.base.Preconditions.checkNotNull;
12 import com.google.common.base.Joiner;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Splitter;
15 import com.google.common.base.Supplier;
16 import java.lang.reflect.Constructor;
17 import java.lang.reflect.InvocationTargetException;
18 import java.lang.reflect.ParameterizedType;
19 import java.lang.reflect.Type;
20 import java.util.List;
21 import java.util.concurrent.Callable;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
25 public final class ClassLoaderUtils {
26 private static final Logger LOG = LoggerFactory.getLogger(ClassLoaderUtils.class);
27 private static final Splitter DOT_SPLITTER = Splitter.on('.');
29 private ClassLoaderUtils() {
30 throw new UnsupportedOperationException("Utility class");
34 * Runs {@link Supplier} with provided {@link ClassLoader}.
36 * Invokes supplies function and makes sure that original {@link ClassLoader}
37 * is context {@link ClassLoader} after execution.
39 * @param cls {@link ClassLoader} to be used.
40 * @param function Function to be executed.
41 * @return Result of supplier invocation.
43 public static <V> V withClassLoader(final ClassLoader cls, final Supplier<V> function) {
44 checkNotNull(cls, "Classloader should not be null");
45 checkNotNull(function, "Function should not be null");
47 final Thread currentThread = Thread.currentThread();
48 final ClassLoader oldCls = currentThread.getContextClassLoader();
50 currentThread.setContextClassLoader(cls);
51 return function.get();
53 currentThread.setContextClassLoader(oldCls);
58 * Runs {@link Callable} with provided {@link ClassLoader}.
60 * Invokes supplies function and makes sure that original {@link ClassLoader}
61 * is context {@link ClassLoader} after execution.
63 * @param cls {@link ClassLoader} to be used.
64 * @param function Function to be executed.
65 * @return Result of callable invocation.
67 public static <V> V withClassLoader(final ClassLoader cls, final Callable<V> function) throws Exception {
68 checkNotNull(cls, "Classloader should not be null");
69 checkNotNull(function, "Function should not be null");
71 final Thread currentThread = Thread.currentThread();
72 final ClassLoader oldCls = currentThread.getContextClassLoader();
74 currentThread.setContextClassLoader(cls);
75 return function.call();
77 currentThread.setContextClassLoader(oldCls);
81 public static Object construct(final Constructor<?> constructor, final List<Object> objects)
82 throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
83 final Object[] initargs = objects.toArray();
84 return constructor.newInstance(initargs);
89 * Loads class using this supplied classloader.
93 * @param name String name of class.
95 * @throws ClassNotFoundException
97 public static Class<?> loadClass(final ClassLoader cls, final String name) throws ClassNotFoundException {
98 if ("byte[]".equals(name)) {
101 if ("char[]".equals(name)) {
104 return loadClass0(cls,name);
107 private static Class<?> loadClass0(final ClassLoader cls, final String name) throws ClassNotFoundException {
109 return cls.loadClass(name);
110 } catch (final ClassNotFoundException e) {
111 final List<String> components = DOT_SPLITTER.splitToList(name);
113 if (isInnerClass(components)) {
114 final int length = components.size() - 1;
115 final String outerName = Joiner.on(".").join(components.subList(0, length));
116 final String innerName = outerName + "$" + components.get(length);
117 return cls.loadClass(innerName);
124 private static boolean isInnerClass(final List<String> components) {
125 final int length = components.size();
130 final String potentialOuter = components.get(length - 2);
131 if (potentialOuter == null) {
134 return Character.isUpperCase(potentialOuter.charAt(0));
137 public static Class<?> loadClassWithTCCL(final String name) throws ClassNotFoundException {
138 return loadClass(Thread.currentThread().getContextClassLoader(), name);
141 public static Class<?> tryToLoadClassWithTCCL(final String fullyQualifiedName) {
143 return loadClassWithTCCL(fullyQualifiedName);
144 } catch (final ClassNotFoundException e) {
145 LOG.debug("Failed to load class {}", fullyQualifiedName, e);
150 public static <S,G,P> Class<P> findFirstGenericArgument(final Class<S> scannedClass, final Class<G> genericType) {
151 return withClassLoader(scannedClass.getClassLoader(), ClassLoaderUtils.findFirstGenericArgumentTask(scannedClass, genericType));
154 private static <S,G,P> Supplier<Class<P>> findFirstGenericArgumentTask(final Class<S> scannedClass, final Class<G> genericType) {
155 return new Supplier<Class<P>>() {
157 @SuppressWarnings("unchecked")
158 public Class<P> get() {
159 final ParameterizedType augmentationGeneric = findParameterizedType(scannedClass, genericType);
160 if (augmentationGeneric != null) {
161 return (Class<P>) augmentationGeneric.getActualTypeArguments()[0];
168 public static ParameterizedType findParameterizedType(final Class<?> subclass, final Class<?> genericType) {
169 Preconditions.checkNotNull(subclass);
170 Preconditions.checkNotNull(genericType);
172 for (final Type type : subclass.getGenericInterfaces()) {
173 if (type instanceof ParameterizedType && genericType.equals(((ParameterizedType) type).getRawType())) {
174 return (ParameterizedType) type;
178 LOG.debug("Class {} does not declare interface {}", subclass, genericType);
182 public static Type getFirstGenericParameter(final Type type) {
183 if (type instanceof ParameterizedType) {
184 return ((ParameterizedType) type).getActualTypeArguments()[0];