org.fax4j.util.ReflectionHelper Maven / Gradle / Ivy
package org.fax4j.util;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* Holds general functions for working with reflection and dynamic invocation
* of code/classes.
*
* @author Sagie Gur-Ari
* @version 1.0
* @since 0.40.6
*/
public final class ReflectionHelper
{
/**
* This is the default constructor.
*/
private ReflectionHelper()
{
super();
}
/**
* This function returns the thread context class loader.
*
* @return The thread context class loader
*/
public static ClassLoader getThreadContextClassLoader()
{
Thread thread=Thread.currentThread();
ClassLoader classLoader=thread.getContextClassLoader();
return classLoader;
}
/**
* This function returns the class based on the class name.
*
* @param className
* The class name of the requested type
* @return The type
* @throws Exception
* Any exception during the loading of the type definition
*/
public static Class> getType(String className) throws Exception
{
ClassLoader classLoader=ReflectionHelper.getThreadContextClassLoader();
Class> type=classLoader.loadClass(className);
return type;
}
/**
* This function creates a new instance of the requested type.
*
* @param type
* The class type
* @return The instance
* @throws Exception
* Any exception during the creation of the instance
*/
public static Object createInstance(Class> type) throws Exception
{
//create instance
Object instance=type.newInstance();
return instance;
}
/**
* This function invokes the requested method.
*
* @param type
* The class type
* @param instance
* The instance
* @param methodName
* The method name to invoke
* @param inputTypes
* An array of input types
* @param input
* The method input
* @return The method output
* @throws Exception
* Any exception while locating/running the method
*/
public static Object invokeMethod(Class> type,Object instance,String methodName,Class>[] inputTypes,Object[] input) throws Exception
{
//get method
Method method=type.getMethod(methodName,inputTypes);
//set accessible
method.setAccessible(true);
//invoke method
Object output=method.invoke(instance,input);
return output;
}
/**
* This function returns the field wrapper for the requested field
*
* @param type
* The class type
* @param fieldName
* The field name
* @return The field
* @throws Exception
* Any exception while locating/running the method
*/
public static Field getField(Class> type,String fieldName) throws Exception
{
//get field
Field field=type.getDeclaredField(fieldName);
//set accessible
field.setAccessible(true);
return field;
}
}