java class遍历属性

private void iterateClass(Object object) {
        Field[] fields = object.getClass().getDeclaredFields();
        for(Field field : fields) {
            String name = field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
            Method m;
            try {
                String methodName = "get" + name;
                List<String> mlist = new ArrayList<>();
                for(Method method : object.getClass().getMethods()) {
                    mlist.add(method.getName());
                }
                if(mlist.contains(methodName)) {
                    m = object.getClass().getMethod("get"+name);
                    Object value = m.invoke(object);
                    System.out.println(name + ":" + value);
                } else {
                    System.out.println(name + ":no such method");
                }
            } catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

 

posted @ 2016-03-31 19:36  無限大  阅读(1651)  评论(0编辑  收藏  举报