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. 在PHP中使用MySQL Mysqli操作数据库 ,以及类操作方法

    先来操作函数部分,普遍的MySQL 函数方法,但随着PHP5的发展,有些函数使用的要求加重了,有些则将废弃不用,有些则参数必填... ================================= ...

  2. Pivot

    测试数据 Create Table TPivot ( ID ,), ProductName ), SalesMonth int, SalesCount int ) insert into TPivot ...

  3. DOM-使用节点

    节点类型 DOM规定:整个文档是一个文档节点,每个标签是一个元素节点,元素包含的文本是文本节点,元素的属性是一个属性节点,注释属于注释节点,如此等等: 每个节点都有一个nodeType属性,用于标明节 ...

  4. [转] PHP读取HTTP接口如何处理超时

    原文地址:https://www.jianshu.com/p/446ea7aaea86 最近在工作中遇到一个读取 HTTP 接口慢的问题(使用的是 PHP 服务器端语言),所以想谈谈服务器端读取外部资 ...

  5. 【转】Cookie深度解析

    Cookie简介 众所周知,Web协议(也就是HTTP)是一个无状态的协议(HTTP1.0).一个Web应用由很多个Web页面组成,每个页面都有唯一的URL来定义.用户在浏览器的地址栏输入页面的URL ...

  6. Android DiskLruCache完全解析,硬盘缓存的最佳方案

    Android DiskLruCache完全解析,硬盘缓存的最佳方案 概述   记得在很早之前,我有写过一篇文章Android高效加载大图.多图解决方案,有效避免程序OOM,这篇文章是翻译自Andro ...

  7. POJ3414(KB1-H BFS)

    Pots Description You are given two pots, having the volume of A and B liters respectively. The follo ...

  8. webpack2引入bootstrap的坑

    在webpack官网教程的代码分离-css章节中,给出的例子是这样的. //安装 ExtractTextWebpackPlugin 如下 npm install --save-dev extract- ...

  9. bzoj3167 [Heoi2013]Sao

    传送门 这题神坑啊……明明是你菜 首先大家都知道原题等价于给每个点分配一个$1$~$n$且两两不同的权值,同时还需要满足一些大于/小于关系的方案数. 先看一眼数据范围,既然写明了$n\le 1000$ ...

  10. js中list 和 map还有string的部分操作

    1.创建list或者数组 var list = []; list中添加元素:list.push("hello");   如果没有先定义为数组类型不能使用 push方法 判断list ...