java使用反射调用对象get方法

  • Post author:
  • Post category:java


private static volatile SimpleDateFormat format = new SimpleDateFormat("yy-MM-dd HH:mm:ss");

    /**
     * 反射获取get值
     *
     * @param obj
     * @return
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public static HashMap<String, String> invokeGetMethod(Object obj) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    	// 获取对象class
        Class<?> aClass = obj.getClass();
        // 获取对象声明字段
        Field[] declaredFields = aClass.getDeclaredFields();
        HashMap<String, String> result = new HashMap<>(127);
        for (Field declaredField : declaredFields) {
            String fieldName = declaredField.getName();
            if("serialVersionUID".equals(fieldName)){
                continue;
            }
            // 拼接方法名
            String firstCharUpper = fieldName.substring(0, 1).toUpperCase();
            String invokeMethodName = "get" + firstCharUpper + fieldName.substring(1);
            // 获取方法
            Method pendingInvokeMethod = aClass.getMethod(invokeMethodName);
            // 执行方法
            Object invokeResult = pendingInvokeMethod.invoke(obj);
            // 下可省略
            if (ObjectUtil.isNull(invokeResult) ){
                result.put(fieldName, "");
            } else if (invokeResult instanceof Date) {
                String date = format.format((Date) invokeResult);
                result.put(fieldName, date);
            } else {
                result.put(fieldName, invokeResult.toString());
            }
        }
        return result;
    }



版权声明:本文为L_Lawrence原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。