ml.shifu.guagua.util.ReflectionUtils Maven / Gradle / Ivy
/*
* Copyright [2013-2014] eBay Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ml.shifu.guagua.util;
import java.lang.reflect.Constructor;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import ml.shifu.guagua.GuaguaRuntimeException;
/**
* {@link ReflectionUtils} is used to get instance from java reflection mechanism.
*
*
* The class should have default constructor for getting instance.
*
*
* {@link Constructor}s are cached but instances are not cached. Each time you will get a new instance.
*/
public final class ReflectionUtils {
/** Do not instantiate. */
private ReflectionUtils() {
}
/**
* Only support constructors with no parameters.
*/
private static final Class>[] EMPTY_ARRAY = new Class[] {};
/**
* This map is used for cache
*/
private static final Map, Constructor>> CONSTRUCTOR_CACHE = new ConcurrentHashMap, Constructor>>();
/**
* Create an object for the given class. The class should have constructor without any parameters.
*
* @param clazz
* class of which an object is created
* @return a new object
* @throws GuaguaRuntimeException
* In case any exception for reflection.
*/
public static T newInstance(Class clazz) {
T result;
try {
@SuppressWarnings("unchecked")
Constructor meth = (Constructor) CONSTRUCTOR_CACHE.get(clazz);
if(meth == null) {
meth = clazz.getDeclaredConstructor(EMPTY_ARRAY);
meth.setAccessible(true);
CONSTRUCTOR_CACHE.put(clazz, meth);
}
result = meth.newInstance();
} catch (Exception e) {
throw new GuaguaRuntimeException(e);
}
return result;
}
/**
* Create an object for the given class. The class should have constructor without any parameters.
*
* @param name
* qualified class name.
* @return a new object
* @throws GuaguaRuntimeException
* In case any exception for reflection.
*/
public static T newInstance(String name) {
try {
@SuppressWarnings("unchecked")
Class clazz = (Class) Class.forName(name);
return newInstance(clazz);
} catch (Exception e) {
throw new GuaguaRuntimeException(e);
}
}
}