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.Supplier;
15 import java.lang.reflect.Constructor;
16 import java.lang.reflect.InvocationTargetException;
17 import java.lang.reflect.ParameterizedType;
18 import java.lang.reflect.Type;
19 import java.util.Arrays;
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);
28 private ClassLoaderUtils() {
29 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.
44 public static <V> V withClassLoader(final ClassLoader cls, final Supplier<V> function) {
45 checkNotNull(cls, "Classloader should not be null");
46 checkNotNull(function, "Function should not be null");
48 final ClassLoader oldCls = Thread.currentThread().getContextClassLoader();
50 Thread.currentThread().setContextClassLoader(cls);
51 return function.get();
53 Thread.currentThread().setContextClassLoader(oldCls);
59 * Runs {@link Callable} with provided {@link ClassLoader}.
61 * Invokes supplies function and makes sure that original {@link ClassLoader}
62 * is context {@link ClassLoader} after execution.
64 * @param cls {@link ClassLoader} to be used.
65 * @param function Function to be executed.
66 * @return Result of callable invocation.
69 public static <V> V withClassLoader(final ClassLoader cls, final Callable<V> function) throws Exception {
70 checkNotNull(cls, "Classloader should not be null");
71 checkNotNull(function, "Function should not be null");
73 final ClassLoader oldCls = Thread.currentThread().getContextClassLoader();
75 Thread.currentThread().setContextClassLoader(cls);
76 return function.call();
78 Thread.currentThread().setContextClassLoader(oldCls);
82 public static Object construct(final Constructor<? extends Object> constructor, final List<Object> objects)
83 throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
84 final Object[] initargs = objects.toArray();
85 return constructor.newInstance(initargs);
90 * Loads class using this supplied classloader.
94 * @param name String name of class.
96 * @throws ClassNotFoundException
98 public static Class<?> loadClass(final ClassLoader cls, final String name) throws ClassNotFoundException {
99 if ("byte[]".equals(name)) {
102 if ("char[]".equals(name)) {
105 return loadClass0(cls,name);
108 private static Class<?> loadClass0(final ClassLoader cls, final String name) throws ClassNotFoundException {
110 return cls.loadClass(name);
111 } catch (final ClassNotFoundException e) {
112 final String[] components = name.split("\\.");
114 if (isInnerClass(components)) {
115 final int length = components.length;
116 final String outerName = Joiner.on(".").join(Arrays.asList(components).subList(0, length - 1));
117 final String innerName = outerName + "$" + components[length-1];
118 return cls.loadClass(innerName);
125 private static boolean isInnerClass(final String[] components) {
126 final int length = components.length;
130 final String potentialOuter = components[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.<S,G,P>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];