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的更多相关文章

  1. Python类中的 私有变量和私有方法

    默认情况下,Python中的成员函数和成员变量都是公开的(public),在python中没有类似public,private等关键词来修饰成员函数和成员变量.在python中定义私有变量只需要在变量 ...

  2. python 类的私有变量和私有方法

    #!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2017/11/08 8:46 # @Author : lijunjiang # @Fil ...

  3. JavaScript 执行环境(执行上下文) 变量对象 作用域链 上下文 块级作用域 私有变量和特权方法

    总结自<高程三>第四章  理解Javascript_12_执行模型浅析   JS的执行环境与作用域  javascript高级程序第三版学习笔记[执行环境.作用域] 在javascript ...

  4. iOS 学习如何声明私有变量和私有方法

    私有变量 首先来说 OC 中没有绝对的私有变量,这么说基于两点原因: 1可修改:   通过KVC  键值编码 来修改私有成员变量的值 2可读取 :  通过底层runtime 获取实例变量Ivar 对应 ...

  5. Python保护变量、私有变量、私有方法

    保护变量.私有变量.私有方法介绍: _xxx: 单下划线开头叫保护变量,意思是只有类对象和子类对象自己能访问到这些变量,此变量不能通过from XXX import xxx 导入: __xxx : 双 ...

  6. 第七章 函数表达式和函数声明,关于this对象 ,私有作用域(function(){})() ,私有变量和特权方法

    一:函数表达式和函数声明 1:函数声明和函数表达式的区别 ①函数声明不需要分号结尾 ②函数声明有函数提升的特点 ③函数声明后面不能跟圆括号直接调用,因为javascript将function关键字当作 ...

  7. js静态私有变量(将方法变成原型模式,被所有实例共享,而方法操作变量,故变量是静态)

    js静态私有变量(将方法变成原型模式,被所有实例共享,而方法操作变量,故变量是静态) 一.总结 1.js函数中的private和public:js函数中的私有变量 var 变量名,公有变量 this. ...

  8. java中遍历类中的属性、调用getter&setter方法

    public static void testReflect(Object model) throws NoSuchMethodException, IllegalAccessException, I ...

  9. .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 ...

随机推荐

  1. JS事件细分

    鼠标相关事件执行顺序 与 onmousedown 事件相关连得事件发生次序( 鼠标左侧/中间 按钮): onmousedown onmouseup onclick 与 onmousedown 事件相关 ...

  2. Hive学习之Locking

    众所周知,数据库必须要能够支持并发.无论在任何时候,允许同一时刻,多个用户能够同时读取或写入.没有必要给用户提供API显示的获取锁,所以所有的锁都是隐式获取的. 在Hive中有两种类型的锁: 共享锁S ...

  3. Python urllib简单使用

    Python的urllib和urllib2模块都做与请求URL相关的操作. 它们最显著的差异为: urllib2可以接受一个Request对象,并以此可以来设置一个URL的headers,但是urll ...

  4. python分布式爬虫打造搜索引擎--------scrapy实现

    最近在网上学习一门关于scrapy爬虫的课程,觉得还不错,以下是目录还在更新中,我觉得有必要好好的做下笔记,研究研究. 第1章 课程介绍 1-1 python分布式爬虫打造搜索引擎简介 07:23 第 ...

  5. 如何使用 Telegram

    Telegram是一款加密的实时通讯软件,本文告诉大家如何使用 这个软件. 在使用之前,需要保证自己已经开了梯子,如果没有梯子,那么就无法使用这个工具. 假如梯子是 127.0.0.1 端口 1080 ...

  6. 鼠标样式——css国际组织

    w3c国际标准组织提供的鼠标样式: http://css-cursor.techstream.org/

  7. [日常] nginx反代websocket

    去年的事 , 随便记记 ============================================================= 2017年11月6日 记录: 获取包的选择状态: d ...

  8. WPF绑定之索引器值变化通知

    背景 在某些应用中,需要在界面上绑定到索引器,并在值发生变化时实时更新. 解决方案 只要将包含索引器的类实现INotifyPropertyChanged接口,并在索引值更改时引发PropertyCha ...

  9. SpringBoot(一)初遇

    环境: IDEA 2018.1.3 , jdk 1.8 , maven 3.3.9 零 第一次接触springboot, 如何学习比较困惑, 思前想后最后决定从文档来学习, 以下为学习中的参考资料: ...

  10. 商城项目,java返回json数据,报错406

    前言: 项目结构为maven,搭建好架构,整合ssm,进行测试, 从数据库中查询数据,返回json数据,结果报错406 问题: 解决: 1,确定项目中json包是否存在(极大可能出于此) 2,处理器适 ...