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;
11 import com.google.common.base.Joiner;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Splitter;
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.List;
20 import java.util.concurrent.Callable;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
24 public final class ClassLoaderUtils {
25 private static final Logger LOG = LoggerFactory.getLogger(ClassLoaderUtils.class);
26 private static final Splitter DOT_SPLITTER = Splitter.on('.');
28 private ClassLoaderUtils() {
29 throw new UnsupportedOperationException("Utility class");
33 * Runs {@link Supplier} with provided {@link ClassLoader}.
35 * Invokes supplies function and makes sure that original {@link ClassLoader}
36 * is context {@link ClassLoader} after execution.
38 * @param cls {@link ClassLoader} to be used.
39 * @param function Function to be executed.
40 * @return Result of supplier invocation.
42 public static <V> V withClassLoader(final ClassLoader cls, final Supplier<V> function) {
43 checkNotNull(cls, "Classloader should not be null");
44 checkNotNull(function, "Function should not be null");
46 final Thread currentThread = Thread.currentThread();
47 final ClassLoader oldCls = currentThread.getContextClassLoader();
49 currentThread.setContextClassLoader(cls);
50 return function.get();
52 currentThread.setContextClassLoader(oldCls);
57 * Runs {@link Callable} with provided {@link ClassLoader}.
59 * Invokes supplies function and makes sure that original {@link ClassLoader}
60 * is context {@link ClassLoader} after execution.
62 * @param cls {@link ClassLoader} to be used.
63 * @param function Function to be executed.
64 * @return Result of callable invocation.
66 public static <V> V withClassLoader(final ClassLoader cls, final Callable<V> function) throws Exception {
67 checkNotNull(cls, "Classloader should not be null");
68 checkNotNull(function, "Function should not be null");
70 final Thread currentThread = Thread.currentThread();
71 final ClassLoader oldCls = currentThread.getContextClassLoader();
73 currentThread.setContextClassLoader(cls);
74 return function.call();
76 currentThread.setContextClassLoader(oldCls);
80 public static Object construct(final Constructor<?> constructor, final List<Object> objects)
81 throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
82 final Object[] initargs = objects.toArray();
83 return constructor.newInstance(initargs);
88 * Loads class using this supplied classloader.
92 * @param name String name of class.
94 * @throws ClassNotFoundException
96 public static Class<?> loadClass(final ClassLoader cls, final String name) throws ClassNotFoundException {
97 if ("byte[]".equals(name)) {
100 if ("char[]".equals(name)) {
103 return loadClass0(cls,name);
106 private static Class<?> loadClass0(final ClassLoader cls, final String name) throws ClassNotFoundException {
108 return cls.loadClass(name);
109 } catch (final ClassNotFoundException e) {
110 final List<String> components = DOT_SPLITTER.splitToList(name);
112 if (isInnerClass(components)) {
113 final int length = components.size() - 1;
114 final String outerName = Joiner.on(".").join(components.subList(0, length));
115 final String innerName = outerName + "$" + components.get(length);
116 return cls.loadClass(innerName);
123 private static boolean isInnerClass(final List<String> components) {
124 final int length = components.size();
129 final String potentialOuter = components.get(length - 2);
130 if (potentialOuter == null) {
133 return Character.isUpperCase(potentialOuter.charAt(0));
136 public static Class<?> loadClassWithTCCL(final String name) throws ClassNotFoundException {
137 return loadClass(Thread.currentThread().getContextClassLoader(), name);
140 public static Class<?> tryToLoadClassWithTCCL(final String fullyQualifiedName) {
142 return loadClassWithTCCL(fullyQualifiedName);
143 } catch (final ClassNotFoundException e) {
144 LOG.debug("Failed to load class {}", fullyQualifiedName, e);
149 public static <S,G,P> Class<P> findFirstGenericArgument(final Class<S> scannedClass, final Class<G> genericType) {
150 return withClassLoader(scannedClass.getClassLoader(), ClassLoaderUtils.findFirstGenericArgumentTask(scannedClass, genericType));
153 private static <S,G,P> Supplier<Class<P>> findFirstGenericArgumentTask(final Class<S> scannedClass, final Class<G> genericType) {
154 return new Supplier<Class<P>>() {
156 @SuppressWarnings("unchecked")
157 public Class<P> get() {
158 final ParameterizedType augmentationGeneric = findParameterizedType(scannedClass, genericType);
159 if (augmentationGeneric != null) {
160 return (Class<P>) augmentationGeneric.getActualTypeArguments()[0];
167 public static ParameterizedType findParameterizedType(final Class<?> subclass, final Class<?> genericType) {
168 Preconditions.checkNotNull(subclass);
169 Preconditions.checkNotNull(genericType);
171 for (final Type type : subclass.getGenericInterfaces()) {
172 if (type instanceof ParameterizedType && genericType.equals(((ParameterizedType) type).getRawType())) {
173 return (ParameterizedType) type;
177 LOG.debug("Class {} does not declare interface {}", subclass, genericType);
181 public static Type getFirstGenericParameter(final Type type) {
182 if (type instanceof ParameterizedType) {
183 return ((ParameterizedType) type).getActualTypeArguments()[0];