关于Javabean或者实体的通用转化器

经过Java的反射机制,能够得到当前类中的方法或者当前实体的方法和实体的具体的每一个值,这个很是灵活,我暂时领悟到这里。java

object是个对象数组

Field[] fields = object.getClass().getDeclaredFields();    返回一个属性的数组ide

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);    //取值的方法get

相关文章
相关标签/搜索