属性反射并获得属性值

    不知道对象属性的属性名,也可以获得属性值。举个例子,将属性中的所有属性名和属性值格式化为:[xx=xx,xx=xx]的形式。

属性反射并获得属性值
/**
     * 拼裝object中的Field为[xx=xx,xx=xx]
     * 
     * @param object
     * @param userName
     * @return
     */
    private static String acqurieDescription(Object object,
            String userName) {
        String key = "";
        String value = "";
        Field f;
        Field[] keys;
        StringBuffer buffer = new StringBuffer();
        keys = object.getClass().getDeclaredFields();
        buffer.append(userName + ",[");
        for (int i = 0; i < keys.length; i++) {
            f = keys[i];
            key = f.getName().toString();
            value = getFieldValue(object, key);
            if (value.equals("")) {
                continue;
            } else {
                buffer.append(key + "=" + value + ",");
            }
        }
        return buffer.toString().substring(0, buffer.toString().length() - 1) + "]";
    }

    /**
     * 获得属性值
     * 
     * @param owner
     * @param fieldName
     * @return
     */
    private static String getFieldValue(Object owner, String fieldName) {
        Object object = invokeMethod(owner, fieldName, null);
        if (object == null) {
            return "";
        } else
            return object.toString();
    }

    /**
     * 执行某个Field的getField方法
     * 
     * @param owner
     * @param fieldName
     * @param args
     * @return
     */
    private static Object invokeMethod(Object owner, String fieldName,
            Object[] args) {
        Class<? extends Object> ownerClass = owner.getClass();
        String methodName = fieldName.substring(0, 1).toUpperCase()
                + fieldName.substring(1);
        Method method = null;
        try {
            method = ownerClass.getMethod("get" + methodName);
        } catch (SecurityException e) {
            logger.error(e.getMessage());
        } catch (NoSuchMethodException e) {
            logger.error(e.getMessage());
            return "";
        }
        try {
            return method.invoke(owner);
        } catch (Exception e) {
            return "";
        }
    }
属性反射并获得属性值

属性反射并获得属性值

上一篇:iOS 第三方自定义Alertview项目MBProcessHud中的重要代码分析


下一篇:(JAVA/SWT/JFACE)[不规则窗口/自定义窗口]实现方案!