获取指定属性名的属性值简易方法

public class ClassUtil {

    private static final String METHOD_PREFIX = "get"; // 约定俗称的getter()方法前缀

    /**
     * 根据field名称获取field的值<br/>
     * 当field允许直接获取的时候,直接返回<br/>
     * 否则通过查找约定俗称的get+Field(field首字母大写)的公共成员方法来获取<br/>
     * 最后直接返回null
     * 
     * @param object
     * @param fieldName
     * @return Object
     * @throws UnsupportedOperationException
     */
    public static Object getValueByFieldName(Object object, String fieldName) {
        if (object == null || fieldName == null || fieldName.isEmpty()) {
            return null;
        }
        Object value = null;
        Class objectClass = object.getClass();
        try {
            Field field = objectClass.getField(fieldName);
            if (field != null) {
                if (field.isAccessible()) {

                    try {
                        value = field.get(object);
                        return value;
                    } catch (Exception e) {
                        // since we have checked the field by Class.getField method,so this won't happened
                    }
                } else {
                    String methodName = METHOD_PREFIX + fieldName.substring(0, 1).toUpperCase()
                                        + fieldName.substring(1);
                    try {
                        Method method = objectClass.getMethod(methodName, null);
                        if (method != null && !method.isAccessible()) {
                            try {
                                value = method.invoke(object, null);
                            } catch (IllegalArgumentException e) {
                            } catch (IllegalAccessException e) {

                            } catch (InvocationTargetException e) {
                                throw new RuntimeException(e);
                            }
                            return value;
                        }
                    } catch (NoSuchMethodException e) {
                        // since we can't find this method,so just break and return null
                    }
                }
            }
        } catch (SecurityException e) {

        } catch (NoSuchFieldException e) {

        }
        return value;
    }

}
 

转载于:https://www.cnblogs.com/bestchenwu/archive/2012/09/13/9655375.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值