/*
* Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.yangtools.util;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.base.Supplier;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.concurrent.Callable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class ClassLoaderUtils {
private static final Logger LOG = LoggerFactory.getLogger(ClassLoaderUtils.class);
private static final Splitter DOT_SPLITTER = Splitter.on('.');
private ClassLoaderUtils() {
throw new UnsupportedOperationException("Utility class");
}
/**
* Runs {@link Supplier} with provided {@link ClassLoader}.
*
*
Invokes supplies function and makes sure that original {@link ClassLoader}
* is context {@link ClassLoader} after execution.
*
* @param cls {@link ClassLoader} to be used.
* @param function Function to be executed.
* @return Result of supplier invocation.
*/
public static V withClassLoader(final ClassLoader cls, final Supplier function) {
checkNotNull(cls, "Classloader should not be null");
checkNotNull(function, "Function should not be null");
final Thread currentThread = Thread.currentThread();
final ClassLoader oldCls = currentThread.getContextClassLoader();
try {
currentThread.setContextClassLoader(cls);
return function.get();
} finally {
currentThread.setContextClassLoader(oldCls);
}
}
/**
* Runs {@link Callable} with provided {@link ClassLoader}.
*
* Invokes supplies function and makes sure that original {@link ClassLoader}
* is context {@link ClassLoader} after execution.
*
* @param cls {@link ClassLoader} to be used.
* @param function Function to be executed.
* @return Result of callable invocation.
*/
public static V withClassLoader(final ClassLoader cls, final Callable function) throws Exception {
checkNotNull(cls, "Classloader should not be null");
checkNotNull(function, "Function should not be null");
final Thread currentThread = Thread.currentThread();
final ClassLoader oldCls = currentThread.getContextClassLoader();
try {
currentThread.setContextClassLoader(cls);
return function.call();
} finally {
currentThread.setContextClassLoader(oldCls);
}
}
public static Object construct(final Constructor> constructor, final List