反射工具类.提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class,被AOP过的真实类等工具函数.java
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.lang.reflect.*;
import java.util.HashMap;
import java.util.Map; /**
* ClassName: Reflections
* @Description: 反射工具类.提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class,被AOP过的真实类等工具函数.
* @author
* @date 2015年9月9日 下午1:02:26
*/
public class Reflections {
private static final String SETTER_PREFIX = "set"; private static final String GETTER_PREFIX = "get"; private static final String CGLIB_CLASS_SEPARATOR = "$$"; private static Logger logger = LoggerFactory.getLogger(Reflections.class); /**
* @Description: 调用Getter方法.
* @param obj
* @param propertyName
* @return
* @return Object
* @throws
* @author feifei.liu
* @date 2015年9月25日 下午7:55:46
*/
public static Object invokeGetter(Object obj, String propertyName) {
String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(propertyName);
return invokeMethod(obj, getterMethodName, new Class[] {}, new Object[] {});
} /**
* @Description: 调用Setter方法, 仅匹配方法名。
* @param obj
* @param propertyName
* @param value
* @return void
* @throws
* @author feifei.liu
* @date 2015年9月25日 下午7:55:59
*/
public static void invokeSetter(Object obj, String propertyName, Object value) {
String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(propertyName);
invokeMethodByName(obj, setterMethodName, new Object[] { value });
} /**
* @Description: 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
* @param obj
* @param fieldName
* @return
* @return Object
* @throws
* @author feifei.liu
* @date 2015年9月25日 下午7:56:13
*/
public static Object getFieldValue(final Object obj, final String fieldName) {
Field field = getAccessibleField(obj, fieldName); if (field == null) {
throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
} Object result = null;
try {
result = field.get(obj);
} catch (IllegalAccessException e) {
logger.error("不可能抛出的异常{}", e.getMessage());
}
return result;
} /**
* @Description: 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
* @param obj
* @param fieldName
* @param value
* @return void
* @throws
* @author feifei.liu
* @date 2015年9月25日 下午7:56:26
*/
public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
Field field = getAccessibleField(obj, fieldName); if (field == null) {
throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
} try {
/*if("false".equals(value) || "true".equals(value)){
Boolean b = new Boolean(value.toString());
boolean b1 = b.booleanValue();
field.set(obj, b1);
}else{
field.set(obj, value);
}*/
field.set(obj, value);
} catch (IllegalAccessException e) {
logger.error("不可能抛出的异常:{}", e.getMessage());
}
} /**
* @Description: 直接调用对象方法, 无视private/protected修饰符.
* 用于一次性调用的情况,否则应使用getAccessibleMethod()函数获得Method后反复调用. 同时匹配方法名+参数类型.
* @param obj
* @param methodName
* @param parameterTypes
* @param args
* @return
* @return Object
* @throws
* @author feifei.liu
* @date 2015年9月25日 下午7:56:33
*/
public static Object invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes,
final Object[] args) {
Method method = getAccessibleMethod(obj, methodName, parameterTypes);
if (method == null) {
throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
} try {
return method.invoke(obj, args);
} catch (Exception e) {
throw convertReflectionExceptionToUnchecked(e);
}
} /**
* @Description: 直接调用对象方法, 无视private/protected修饰符,
* 用于一次性调用的情况,否则应使用getAccessibleMethodByName()函数获得Method后反复调用.
* 只匹配函数名,如果有多个同名函数调用第一个.
* @param obj
* @param methodName
* @param args
* @return
* @return Object
* @throws
* @author feifei.liu
* @date 2015年9月25日 下午7:56:57
*/
public static Object invokeMethodByName(final Object obj, final String methodName, final Object[] args) {
Method method = getAccessibleMethodByName(obj, methodName);
if (method == null) {
throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
} try {
return method.invoke(obj, args);
} catch (Exception e) {
throw convertReflectionExceptionToUnchecked(e);
}
} /**
* @Description: 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.
* 如向上转型到Object仍无法找到, 返回null.
* @param obj
* @param fieldName
* @return
* @return Field
* @throws
* @author feifei.liu
* @date 2015年9月25日 下午7:57:39
*/
public static Field getAccessibleField(final Object obj, final String fieldName) {
Validate.notNull(obj, "object can't be null");
Validate.notBlank(fieldName, "fieldName can't be blank");
for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass
.getSuperclass()) {
try {
Field field = superClass.getDeclaredField(fieldName);
makeAccessible(field);
return field;
} catch (NoSuchFieldException e) {// NOSONAR
// Field不在当前类定义,继续向上转型
}
}
return null;
} /**
* @Description: 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问. 如向上转型到Object仍无法找到, 返回null.
* 匹配函数名+参数类型.
* 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object...args).
* @param obj
* @param methodName
* @param parameterTypes
* @return
* @return Method
* @throws
* @author feifei.liu
* @date 2015年9月25日 下午7:57:57
*/
public static Method getAccessibleMethod(final Object obj, final String methodName,
final Class<?>... parameterTypes) {
Validate.notNull(obj, "object can't be null");
Validate.notBlank(methodName, "methodName can't be blank"); for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType
.getSuperclass()) {
try {
Method method = searchType.getDeclaredMethod(methodName, parameterTypes);
makeAccessible(method);
return method;
} catch (NoSuchMethodException e) {
// Method不在当前类定义,继续向上转型
}
}
return null;
} /**
* @Description: 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问. 如向上转型到Object仍无法找到, 返回null. 只匹配函数名.
* 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object...args)
* @param obj
* @param methodName
* @return
* @return Method
* @throws
* @author feifei.liu
* @date 2015年9月25日 下午7:58:48
*/
public static Method getAccessibleMethodByName(final Object obj, final String methodName) {
Validate.notNull(obj, "object can't be null");
Validate.notBlank(methodName, "methodName can't be blank"); for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType
.getSuperclass()) {
Method[] methods = searchType.getDeclaredMethods();
for (Method method : methods) {
if (method.getName().equals(methodName)) {
makeAccessible(method);
return method;
}
}
}
return null;
} /**
* @Description: 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨
* @param method
* @return void
* @throws
* @author feifei.liu
* @date 2015年9月25日 下午7:59:24
*/
public static void makeAccessible(Method method) {
if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
&& !method.isAccessible()) {
method.setAccessible(true);
}
} /**
* @Description: 改变private/protected的成员变量为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨
* @param field
* @return void
* @throws
* @author feifei.liu
* @date 2015年9月25日 下午7:59:40
*/
public static void makeAccessible(Field field) {
if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())
|| Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
field.setAccessible(true);
}
} /**
* @Description: 通过反射, 获得Class定义中声明的泛型参数的类型, 注意泛型必须定义在父类处 如无法找到, 返回Object.class. eg.
* @param clazz
* @return
* @return Class<T>
* @throws
* @author feifei.liu
* @date 2015年9月25日 下午7:59:53
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> Class<T> getClassGenricType(final Class clazz) {
return getClassGenricType(clazz, 0);
} /**
* @Description: 通过反射, 获得Class定义中声明的父类的泛型参数的类型. 如无法找到, 返回Object.class.
* @param clazz
* @param index
* @return
* @return Class
* @throws
* @author feifei.liu
* @date 2015年9月25日 下午8:00:07
*/
@SuppressWarnings("rawtypes")
public static Class getClassGenricType(final Class clazz, final int index) { Type genType = clazz.getGenericSuperclass(); if (!(genType instanceof ParameterizedType)) {
logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
return Object.class;
} Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); if ((index >= params.length) || (index < 0)) {
logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
+ params.length);
return Object.class;
}
if (!(params[index] instanceof Class)) {
logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
return Object.class;
} return (Class) params[index];
} /**
* @Description: 通过反射,获得当前对象类型
* @param instance
* @return
* @return Class<?>
* @throws
* @author feifei.liu
* @date 2015年9月25日 下午8:00:29
*/
@SuppressWarnings("rawtypes")
public static Class<?> getUserClass(Object instance) {
Validate.notNull(instance, "Instance must not be null");
Class clazz = instance.getClass();
if ((clazz != null) && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) {
Class<?> superClass = clazz.getSuperclass();
if ((superClass != null) && !Object.class.equals(superClass)) {
return superClass;
}
}
return clazz; } /**
* @Description: 将反射时的checked exception转换为unchecked exception.
* @param e
* @return
* @return RuntimeException
* @throws
* @author feifei.liu
* @date 2015年9月25日 下午8:01:08
*/
public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
if ((e instanceof IllegalAccessException) || (e instanceof IllegalArgumentException)
|| (e instanceof NoSuchMethodException)) {
return new IllegalArgumentException(e);
} else if (e instanceof InvocationTargetException) {
return new RuntimeException(((InvocationTargetException) e).getTargetException());
} else if (e instanceof RuntimeException) {
return (RuntimeException) e;
}
return new RuntimeException("Unexpected Checked Exception.", e);
} /**
* @Description: 循环向上,获取对象声明的字段
* @author xiaopeng.ma
* @date 2017/3/23 17:03
*/
public static Map<String, String> getAllDeclaredField(T t) {
Map<String, String> map = new HashMap<>();
if (t != null) {
Class<?> clazz = t.getClass();
for (; Object.class != clazz; clazz.getSuperclass()) {
Field[] declaredFields = clazz.getDeclaredFields();
for (Field declaredField : declaredFields) {
map.put(declaredField.getName(), declaredField.getClass().getSimpleName());
}
}
}
return map;
} }
反射工具类.提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class,被AOP过的真实类等工具函数.java的更多相关文章
- Python类中的 私有变量和私有方法
默认情况下,Python中的成员函数和成员变量都是公开的(public),在python中没有类似public,private等关键词来修饰成员函数和成员变量.在python中定义私有变量只需要在变量 ...
- python 类的私有变量和私有方法
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2017/11/08 8:46 # @Author : lijunjiang # @Fil ...
- JavaScript 执行环境(执行上下文) 变量对象 作用域链 上下文 块级作用域 私有变量和特权方法
总结自<高程三>第四章 理解Javascript_12_执行模型浅析 JS的执行环境与作用域 javascript高级程序第三版学习笔记[执行环境.作用域] 在javascript ...
- iOS 学习如何声明私有变量和私有方法
私有变量 首先来说 OC 中没有绝对的私有变量,这么说基于两点原因: 1可修改: 通过KVC 键值编码 来修改私有成员变量的值 2可读取 : 通过底层runtime 获取实例变量Ivar 对应 ...
- Python保护变量、私有变量、私有方法
保护变量.私有变量.私有方法介绍: _xxx: 单下划线开头叫保护变量,意思是只有类对象和子类对象自己能访问到这些变量,此变量不能通过from XXX import xxx 导入: __xxx : 双 ...
- 第七章 函数表达式和函数声明,关于this对象 ,私有作用域(function(){})() ,私有变量和特权方法
一:函数表达式和函数声明 1:函数声明和函数表达式的区别 ①函数声明不需要分号结尾 ②函数声明有函数提升的特点 ③函数声明后面不能跟圆括号直接调用,因为javascript将function关键字当作 ...
- js静态私有变量(将方法变成原型模式,被所有实例共享,而方法操作变量,故变量是静态)
js静态私有变量(将方法变成原型模式,被所有实例共享,而方法操作变量,故变量是静态) 一.总结 1.js函数中的private和public:js函数中的私有变量 var 变量名,公有变量 this. ...
- java中遍历类中的属性、调用getter&setter方法
public static void testReflect(Object model) throws NoSuchMethodException, IllegalAccessException, I ...
- .net 反射访问私有变量和私有方法 如何创建C# Closure ? C# 批量生成随机密码,必须包含数字和字母,并用加密算法加密 C#中的foreach和yield 数组为什么可以使用linq查询 C#中的 具名参数 和 可选参数 显示实现接口 异步CTP(Async CTP)为什么那样工作? C#多线程基础,适合新手了解 C#加快Bitmap的访问速度 C#实现对图片文件的压
以下为本次实践代码: using System; using System.Collections.Generic; using System.ComponentModel; using System ...
随机推荐
- 在PHP中使用MySQL Mysqli操作数据库 ,以及类操作方法
先来操作函数部分,普遍的MySQL 函数方法,但随着PHP5的发展,有些函数使用的要求加重了,有些则将废弃不用,有些则参数必填... ================================= ...
- TryParse用法示例
int.Parse()是一种类型转换:表示将数字内容的字符串转为int类型.如果字符串为空,则抛出ArgumentNullException异常:如果字符串内容不是数字,则抛出FormatExce ...
- 导出为shape文件
private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)//导出为s ...
- Java - 延迟初始化
延迟初始化(lazy initialization),也就是在真正被使用的时候才开始初始化的技巧. 不论是静态还是实例,都可以进行延迟初始化. 其本质是初始化开销和访问开销之间的权衡. 毕竟是一种优化 ...
- 数组的strong copy理解
一.数组的不同情况下的copy,mutablecopy分析 1.不可变数组的copy(没有创建新对象,复制的只是指针) 2.不可变数组的mutable copy(创建新对象) ...
- JAVA实现加入收藏和设为首页---网摘
JS:加入收藏夹<script language="javascript">function bookmark(){window.external.AddFavorit ...
- 【转】Cookie深度解析
Cookie简介 众所周知,Web协议(也就是HTTP)是一个无状态的协议(HTTP1.0).一个Web应用由很多个Web页面组成,每个页面都有唯一的URL来定义.用户在浏览器的地址栏输入页面的URL ...
- jstack,jmap,jstat分别的意义
1.Jstack 1.1 jstack能得到运行java程序的java stack和native stack的信息.可以轻松得知当前线程的运行情况.如下图所示 注:这个和thread dump是同 ...
- Oracle ORA12514 监听程序当前无法识别连接描述符中请求的服务
在连接数据库的时候,有时会遇到一个“ORA12514:监听程序当前无法识别连接描述符中请求的服务”的错误,这个错误其实就是数据库动态注册(关于动态注册会在稍后讲解)不生效,导致监听器无法识别客户端连接 ...
- 深入理解JVM之JVM内存区域与内存分配
深入理解JVM之JVM内存区域与内存分配 在学习jvm的内存分配的时候,看到的这篇博客,该博客对jvm的内存分配总结的很好,同时也利用jvm的内存模型解释了java程序中有关参数传递的问题. 博客出处 ...