1、设值
/**
* 根据属性名设置属性值
*
* @param fieldName
* @param object
* @return
*/
public boolean setFieldValueByFieldName(String fieldName, Object object,String value) {
try {
// 获取obj类的字节文件对象
Class c = object.getClass();
// 获取该类的成员变量
Field f = c.getDeclaredField(fieldName);
// 取消语言访问检查
f.setAccessible(true);
// 给变量赋值
f.set(object, value);
return true;
} catch (Exception e) {
log.error("反射取值异常",e);
return false;
}
}
2、取值
/**
* 根据属性名获取属性值
*
* @param fieldName
* @param object
* @return
*/
public Object getFieldValueByFieldName(String fieldName, Object object) {
try {
Field field = object.getClass().getDeclaredField(fieldName);
//设置对象的访问权限,保证对private的属性的访问
field.setAccessible(true);
return field.get(object);
} catch (Exception e) {
log.error("反射设值异常",e);
return null;
}
}
3、反射调用无参方法
public void execution(String className, String methodName) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Class<?> aClass = Class.forName(className);
Object obj = aClass.newInstance();
Method method = aClass.getMethod(methodName);
method.invoke(obj);
}
4、反射调用有参方法
/**
* 这里只列举只有一个参数的情况,多个类似
*
* @param className
* @param methodName
* @param parameter 参数
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws NoSuchMethodException
* @throws InvocationTargetException
*/
public void execution(String className, String methodName, Object parameter) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Class<?> aClass = Class.forName(className);
Object obj = aClass.newInstance();
Method method = aClass.getMethod(methodName, parameter.getClass());
method.invoke(obj, parameter);
}
5、反射调用方法(无参也适用)
/**
* 反射调用方法
*
* @param className 全限定类名,例如:com.xiaostudy.test.Mytest1
* @param methodName 方法名,例如:show
* @param parameters 0或多个参数
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws NoSuchMethodException
* @throws InvocationTargetException
*/
public static void execution(String className, String methodName, Object... parameters) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Class<?> aClass = Class.forName(className);
Object obj = aClass.newInstance();
Class[] classes = new Class[parameters.length];for (int i = 0, length = parameters.length; i < length; i++) {
classes[i] = parameters[i].getClass();
}
Method method = aClass.getMethod(methodName, classes);
method.invoke(obj, parameters);
}