關於Javabean或者實體的通用轉化器

通過Java的反射機制,可以獲得當前類中的方法或者當前實體的方法和實體的具體的每個值,這個非常靈活,我暫時領悟到這裏。

object是個對象

Field[] fields = object.getClass().getDeclaredFields();    返回一個屬性的數組

Method[] methods = object.getClass().getMethods();         方法


下面放出代碼:用了遞歸


public static String tt(Object object){
    if(object!=null){
    String className = object.getClass().getName();
    System.out.println("---:"+className);
    if(className.startsWith("java.util.")){
        System.out.println("3---:"+className);
        List<Object> list = (List<Object>) object;
        for (Object object2 : list) {
            tt(object);
        }
    }else if(!className.startsWith("java")){
        System.out.println("2---:"+className);
    Field[] fields = object.getClass().getDeclaredFields();
    Method[] methods = object.getClass().getMethods();
    //得到類所有屬性
            for (int i = 0; i < fields.length; i++) {
                String propertyName = fields[i].getName();
                System.out.println("propertyName:"+propertyName);
                String propertyGetName = NULL_VALUE;
                if (propertyName != null && !NULL_VALUE.equals(propertyName)) {
                    propertyGetName = GET+propertyName.toLowerCase();
                }else {
                    return null;
                }
                             
                //獲取所有方法
                for (int j = 0; j < methods.length; j++) {
                    String methodName = methods[j].getName();
                    if (methodName != null && !NULL_VALUE.equals(methodName)) {
                        methodName = methodName.toLowerCase();
                    }else {
                        return null;
                    }
                    //執行所有訪問器
                    if (methodName.equals(propertyGetName)) {//....
                        try {
                            Object propertyValue = methods[j].invoke(object, null);
                            System.out.println("propertyValue::"+propertyValue);
                            tt(propertyValue);
                        } catch (Exception e) {
                            System.out.println(" >>> get method exception!");
                            e.printStackTrace();
                        }
                    }
                }
            }
    }
    }
            return null;
}



Object propertyValue = methods[j].invoke(object, null);    //取值的方法

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章