package com.test.unit.util;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* 反射相关函数
*
*/
public class AboutReflect {
/**
* 触发对象方法
*
* @param obj 方法所在对象
* @param methodName 方法名
* @param classes 参数类型
* @param objects 参数
* @return
*/
public static Object invoke(final Object obj, final String methodName, final Class[] classes,
final Object[] objects) {
try {
Method method = getMethod(obj.getClass(), methodName, classes);
method.setAccessible(true);
return method.invoke(obj, objects);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 获取对象的方法
*
* @param classParam 方法存在的类对象
* @param methodName 方法名
* @param classes 参数类型
* @return 该对象的方法
* @throws Exception
*/
public static Method getMethod(Class classParam, String methodName, final Class[] classes)
throws Exception {
Method method = null;
try {
method = classParam.getDeclaredMethod(methodName, classes);
} catch (NoSuchMethodException e) {
try {
method = classParam.getMethod(methodName, classes);
} catch (NoSuchMethodException ex) {
if (classParam.getSuperclass() == null) {
return method;
} else {
method = getMethod(classParam.getSuperclass(), methodName, classes);
}
}
}
return method;
}
/**
* 设置类对象中变量值
*
* @param obj 需要设变量值的类对象
* @param fieldName 变量值名
* @param value 变量值
*/
public static void setFiled(Object obj, String fieldName, Object value) {
Class dc = obj.getClass();
try {
Field field = dc.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(obj, value);
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}