/**
* 通过反射获取未公开的方法
*
* @param clazz 需要反射获取的类名
* @param clsMethod 参数名
* @param methodName 方法名
* @param obj 需要赋值的对象
* @param value 待设置的值
*/
private static void getMethodByReflection(final Class<?> clazz, final Class<?> clsMethod, final String methodName, Object obj, Object value) {
if (null == clazz || null == clsMethod || null == methodName || null == obj) {
JLog.e(TAG, "getMethodByReflection has parameter is null ");
return;
}
try {
Method method = clazz.getDeclaredMethod(methodName, clsMethod);
// 私有方法赋予权限
method.setAccessible(true);
method.invoke(obj, value);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
JLog.e(TAG, "getMethodByReflection error: " + e.getMessage());
}
}
private static void getFieldByReflection(final Class<?> clazz, final String fieldName, Object obj, Object value){
try {
Field path = clazz.getDeclaredField(fieldName);
path.setAccessible(true);//启用私有变量可赋值权限
path.set(obj,value);
} catch (NoSuchFieldException|IllegalAccessException e) {
e.printStackTrace();
}
}
网友评论