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");
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 List<String> components = DOT_SPLITTER.splitToList(name);
114 if (isInnerClass(components)) {
115 final int length = components.size() - 1;
116 final String outerName = Joiner.on(".").join(components.subList(0, length));
117 final String innerName = outerName + "$" + components.get(length);
118 return cls.loadClass(innerName);
125 private static boolean isInnerClass(final List<String> components) {
126 final int length = components.size();
131 final String potentialOuter = components.get(length - 2);
132 if (potentialOuter == null) {
135 return Character.isUpperCase(potentialOuter.charAt(0));
138 public static Class<?> loadClassWithTCCL(final String name) throws ClassNotFoundException {
139 return loadClass(Thread.currentThread().getContextClassLoader(), name);
142 public static Class<?> tryToLoadClassWithTCCL(final String fullyQualifiedName) {
144 return loadClassWithTCCL(fullyQualifiedName);
145 } catch (final ClassNotFoundException e) {
146 LOG.debug("Failed to load class {}", fullyQualifiedName, e);
151 public static <S,G,P> Class<P> findFirstGenericArgument(final Class<S> scannedClass, final Class<G> genericType) {
152 return withClassLoader(scannedClass.getClassLoader(), ClassLoaderUtils.<S,G,P>findFirstGenericArgumentTask(scannedClass, genericType));
155 private static <S,G,P> Supplier<Class<P>> findFirstGenericArgumentTask(final Class<S> scannedClass, final Class<G> genericType) {
156 return new Supplier<Class<P>>() {
158 @SuppressWarnings("unchecked")
159 public Class<P> get() {
160 final ParameterizedType augmentationGeneric = findParameterizedType(scannedClass, genericType);
161 if (augmentationGeneric != null) {
162 return (Class<P>) augmentationGeneric.getActualTypeArguments()[0];
169 public static ParameterizedType findParameterizedType(final Class<?> subclass, final Class<?> genericType) {
170 Preconditions.checkNotNull(subclass);
171 Preconditions.checkNotNull(genericType);
173 for (final Type type : subclass.getGenericInterfaces()) {
174 if (type instanceof ParameterizedType && genericType.equals(((ParameterizedType) type).getRawType())) {
175 return (ParameterizedType) type;
179 LOG.debug("Class {} does not declare interface {}", subclass, genericType);
183 public static Type getFirstGenericParameter(final Type type) {
184 if (type instanceof ParameterizedType) {
185 return ((ParameterizedType) type).getActualTypeArguments()[0];