反射工具类,通过getMethod和setMethod进行操作

  由于公司封装了反射的一些工具类,感觉挺好用的,所以在这里记录下吧

  比如:

一,通过getMethod获取返回值

private static final String SETTER_PREFIX = "set";

private static final String GETTER_PREFIX = "get";

private static final String CGLIB_CLASS_SEPARATOR = "$$";

/**
 * 调用Getter方法.
 * 支持多级,如:对象名.对象名.方法
 */
public static Object invokeGetter(Object obj, String propertyName) {
    Object object = obj;
    for (String name : StringUtils.split(propertyName, ".")) {
        String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name);
        object = invokeMethod(object, getterMethodName, new Class[]{}, new Object[]{});
    }
    return object;
}
通过此方法可以调用实体的get方法,可以支持级联,用法比如:
Student student = new Student();
student.setStudentName("zhangshan");
User user = new User();
user.setStudent(student);
String studentName = (String) Reflections.invokeGetter(user,"student.studentName");
System.out.println(studentName);
二,通过setMethod,写入参数
/**
 * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
 * 如向上转型到Object仍无法找到, 返回null.
 * 匹配函数名+参数类型。
 * <p/>
 * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
 */
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不在当前类定义,继续向上转型
            continue;// new add
        }
    }
    return null;
}
/**
 * 直接调用对象方法, 无视private/protected修饰符.
 * 用于一次性调用的情况,否则应使用getAccessibleMethod()函数获得Method后反复调用.
 * 同时匹配方法名+参数类型,
 */
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);
    }
}
/**
 * 直接调用对象方法, 无视private/protected修饰符,
 * 用于一次性调用的情况,否则应使用getAccessibleMethodByName()函数获得Method后反复调用.
 * 只匹配函数名,如果有多个同名函数调用第一个。
 */
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);
    }
}
/**
 * 调用Setter方法, 仅匹配方法名。
 * 支持多级,如:对象名.对象名.方法
 */
public static void invokeSetter(Object obj, String propertyName, Object value) {
    Object object = obj;
    String[] names = StringUtils.split(propertyName, ".");
    for (int i = 0; i < names.length; i++) {
        if (i < names.length - 1) {
            String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]);
            object = invokeMethod(object, getterMethodName, new Class[]{}, new Object[]{});
        } else {
            String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]);
            invokeMethodByName(object, setterMethodName, new Object[]{value});
        }
    }
}
用法如下:
Student student = new Student();
User user = new User();
user.setStudent(student);
Reflections.invokeSetter(user,"student.studentName","hehe");
String studentName = user.getStud().getStudentName();
System.out.println(studentName);



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值