java reflect method_通过java.lang.reflect.Method/Field方法属性反射工具类ReflectUtils实现获取属性set/getter方法调用等操作...

一、前言

关于通过java.lang.reflect.Field/java.lang.reflect.Method反射属性方法实现ReflectUtils工具类,实现了基于class创建实例createInstance方法、属性Field类对象实例获取属性值、类对象实例指定property属性字符串获取值invokeGetter、类对象实例指定方法反射调用invokeMethod、给类属性setter值进行反射调用赋值setField等操作。

二、代码示例import java.lang.reflect.Field;@b@import java.lang.reflect.Method;@b@import java.util.Arrays;@b@@b@public class ReflectUtils@b@{@b@  public static  T createInstance(Class> clazz)@b@  {@b@    try@b@    {@b@      if (clazz == null)@b@        return null;@b@@b@      return clazz.newInstance();@b@    }@b@    catch (Exception e) {@b@      throw new RuntimeException("Error occured during creating instance of " + clazz, e);@b@    }@b@  }@b@@b@  public static Object getField(Field field, Object instance) throws RuntimeException {@b@    try {@b@      if (!(field.isAccessible())) {@b@        field.setAccessible(true);@b@      }@b@@b@      return field.get(instance);@b@    } catch (Exception e) {@b@      throw new RuntimeException("Error occured during getting field: " + field, e.getCause());@b@    }@b@  }@b@@b@  public static Object invokeGetter(Object instance, String property) {@b@    Method getter;@b@    Class clazz = instance.getClass();@b@    try@b@    {@b@      getter = clazz.getMethod("get" + Character.toUpperCase(property.charAt(0)) + property.substring(1), new Class[0]);@b@    } catch (Exception e) {@b@      throw new RuntimeException("No getter method found: " + e, e);@b@    }@b@@b@    return invokeMethod(getter, instance, new Object[0]);@b@  }@b@@b@  public static Object invokeMethod(Method method, Object instance, Object[] parameters) throws RuntimeException {@b@    try {@b@      return method.invoke(instance, parameters);@b@    }@b@    catch (Exception e) {@b@      throw new RuntimeException("Error occured during invoking method: " + method + " with parameters(" + @b@        Arrays.asList(parameters)@b@         + ")", e.getCause());@b@    }@b@  }@b@@b@  public static void setField(Field field, Object instance, Object value) throws RuntimeException {@b@    try {@b@      if (!(field.isAccessible())) {@b@        field.setAccessible(true);@b@      }@b@@b@      field.set(instance, value);@b@    }@b@    catch (Exception e) {@b@      throw new RuntimeException("Error occured during setting field: " + field + " with value(" + value + ")", e@b@        .getCause());@b@    }@b@  }@b@}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值