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}.
37 * Invokes supplies function and makes sure that original {@link ClassLoader}
38 * is context {@link ClassLoader} after execution.
40 * @param cls {@link ClassLoader} to be used.
41 * @param function Function to be executed.
42 * @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 Thread currentThread = Thread.currentThread();
49 final ClassLoader oldCls = currentThread.getContextClassLoader();
51 currentThread.setContextClassLoader(cls);
52 return function.get();
54 currentThread.setContextClassLoader(oldCls);
59 * Runs {@link Callable} with provided {@link ClassLoader}.
62 * Invokes supplies function and makes sure that original {@link ClassLoader}
63 * is context {@link ClassLoader} after execution.
65 * @param cls {@link ClassLoader} to be used.
66 * @param function Function to be executed.
67 * @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 Thread currentThread = Thread.currentThread();
74 final ClassLoader oldCls = currentThread.getContextClassLoader();
76 currentThread.setContextClassLoader(cls);
77 return function.call();
79 currentThread.setContextClassLoader(oldCls);
83 public static Object construct(final Constructor<?> constructor, final List<Object> objects)
84 throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
85 final Object[] initargs = objects.toArray();
86 return constructor.newInstance(initargs);
90 * Loads class using this supplied classloader.
92 * @param name String name of class.
94 public static Class<?> loadClass(final ClassLoader cls, final String name) throws ClassNotFoundException {
95 if ("byte[]".equals(name)) {
98 if ("char[]".equals(name)) {
101 return loadClass0(cls,name);
104 private static Class<?> loadClass0(final ClassLoader cls, final String name) throws ClassNotFoundException {
106 return cls.loadClass(name);
107 } catch (final ClassNotFoundException e) {
108 final List<String> components = DOT_SPLITTER.splitToList(name);
110 if (isInnerClass(components)) {
111 final int length = components.size() - 1;
112 final String outerName = Joiner.on(".").join(components.subList(0, length));
113 final String innerName = outerName + "$" + components.get(length);
114 return cls.loadClass(innerName);
121 private static boolean isInnerClass(final List<String> components) {
122 final int length = components.size();
127 final String potentialOuter = components.get(length - 2);
128 if (potentialOuter == null) {
131 return Character.isUpperCase(potentialOuter.charAt(0));
134 public static Class<?> loadClassWithTCCL(final String name) throws ClassNotFoundException {
135 return loadClass(Thread.currentThread().getContextClassLoader(), name);
138 public static Class<?> tryToLoadClassWithTCCL(final String fullyQualifiedName) {
140 return loadClassWithTCCL(fullyQualifiedName);
141 } catch (final ClassNotFoundException e) {
142 LOG.debug("Failed to load class {}", fullyQualifiedName, e);
147 public static <S,G,P> Class<P> findFirstGenericArgument(final Class<S> scannedClass, final Class<G> genericType) {
148 return withClassLoader(scannedClass.getClassLoader(), findFirstGenericArgumentTask(scannedClass, genericType));
151 @SuppressWarnings("unchecked")
152 private static <S, G, P> Supplier<Class<P>> findFirstGenericArgumentTask(final Class<S> scannedClass,
153 final Class<G> genericType) {
155 final ParameterizedType augmentationGeneric = findParameterizedType(scannedClass, genericType);
156 if (augmentationGeneric != null) {
157 return (Class<P>) augmentationGeneric.getActualTypeArguments()[0];
163 public static ParameterizedType findParameterizedType(final Class<?> subclass, final Class<?> genericType) {
164 Preconditions.checkNotNull(subclass);
165 Preconditions.checkNotNull(genericType);
167 for (final Type type : subclass.getGenericInterfaces()) {
168 if (type instanceof ParameterizedType && genericType.equals(((ParameterizedType) type).getRawType())) {
169 return (ParameterizedType) type;
173 LOG.debug("Class {} does not declare interface {}", subclass, genericType);
177 public static Type getFirstGenericParameter(final Type type) {
178 if (type instanceof ParameterizedType) {
179 return ((ParameterizedType) type).getActualTypeArguments()[0];