`

通过反映射调用私有方法

 
阅读更多

public class ClassMethodUtil {

/**
* @author yuxin 执行对象内特定的私有或公用函数
* @param clsType
* 函数所在的类
* @param obj
* 函数所在的对象
* @param methodName
* 函数名称
* @param parameterTypes
* 函数参数的类型数组
* @param args
* 函数参数数组
* @return 方法执行后的返回值
*/
public static Object methoInvoke(Class clsType, Object obj,String methodName, Class[] parameterTypes, Object[] args)
throws Exception {
try {
Method method = clsType.getDeclaredMethod(methodName,
parameterTypes);
method.setAccessible(true);
return method.invoke(obj, args);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception(e);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception(e);
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception(e);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception(e);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception(e);
}
}

/**
* @author yuxin 取得对象内特定的私有或公用字段
* @param clsType
* 字段所在的类
* @param obj
* 字段所在的对象
* @param fieldName
* 字段名称
* @return 字段值
*/
public static Object getField(Class clsType, Object obj, String fieldName)
throws Exception {
try {
Field field = clsType.getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(obj);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception(e);
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception(e);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception(e);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception(e);
}

}

/**
* @author yuxin 取得对象内特定的私有或公用字段
* @param clsType
* 字段所在的类
* @param obj
* 字段所在的对象
* @param fieldName
* 字段名称
* @param value
* 字段值
*/
public static void setField(Class clsType, Object obj, String fieldName,
Object value) throws Exception {
try {
Field field = clsType.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(obj, value);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception(e);
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception(e);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception(e);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception(e);
}

}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics