反射工具类.提供调用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 ...
随机推荐
- JAVA GUID
import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Exec ...
- docker改国内官方镜像
如何使用官方镜像 Docker 中国官方镜像加速可通过 registry.docker-cn.com 访问.目前该镜像库只包含流行的公有镜像,而私有镜像仍需要从美国镜像库中拉取. 您可以使用以下命令直 ...
- SQLAlchemy使用说明之ORM
对象关系映射(Object Relation Map, ORM)可以将一个类映射为关系模式(数据表). 使用ORM比直接书写SQL在安全性,可读性上都有很大优势. Working with Relat ...
- 基于python的多线程暴破脚本
搭建了一个本地wordpress,写一个基于多线程异步I/O的暴力破解 1 测试 提交错误的表单数据时,查看请求参数 登录时发送的cookie 2 登录分析 经过多次测试,发现无论是输入正确的密码还是 ...
- The "tsconfig.json" file must have compilerOptions.sourceMap set to true
在编译ionic项目的时候出现:Error:The "tsconfig.json" file must have compilerOptions.sourceMap set to ...
- 通向全栈之路——(4)nginx反向代理配置
1.安装nginx:sudo apt-get install nginx2.新建配置文件:cd /etc/nginx/conf.dsudo vi XXX-cn-8080.conf内容如下:upstre ...
- 一:Web
一:Web介绍 1.Web:网页,网络 2.Web应用:运行在网络上的应用程序 3.网络应用程序分类:C/S B/S C/S 客服端(client)/服务器(server) 典型应用:QQ,YY B/ ...
- 无法解决 equal to 运算中 "Chinese_PRC_CI_AS" 和 "Latin1_General_100_CI_AS" 之间的排序规则冲突。
问题 操作临时表时提示如下排序规则冲突错误 sql ....忽略...sql ..... 无法解决 equal to 运算中 "Chinese_PRC_CI_AS" 和 " ...
- @valid注解
今天发现一个非常好用的注解直接上代码: 实体类domain: @Column(name = "NAME") @NotNull @Size(min = 2,max = 50) pri ...
- UNIX 高手的另外 10 个习惯
让我们面对现实吧:坏习惯很难改变.但是您已经熟悉的习惯可能更难克服.有时,重新审视某些事情可能让您遇到“啊哈,我没想到它能做到这一点!”的时刻.在 Michael Stutz 的优秀文章“UNIX 高 ...