欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

利用反射遍历一个POJO对象的各个字段名及属性

程序员文章站 2022-05-30 16:28:51
...
public class ReflectionFiledPrintTest {   
    private String name = "GoGoGo";   
  
    private String city = "DoDoDo";   
  
    public String getCity() {   
        return city;   
    }   
  
    public void setCity(String city) {   
        this.city = city;   
    }   
  
    public String getName() {   
        return name;   
    }   
  
    public void setName(String name) {   
        this.name = name;   
    }   
  
    public static void main(String args[]) {   
        Object obj = "222";   
        System.out.println("111"+obj);   
        ReflectionFiledPrintTest tfpt = new ReflectionFiledPrintTest();   
        try {   
            Class reClass = Class   
                    .forName("reflection.ReflectionFiledPrintTest");   
            Method methods[] = reClass.getDeclaredMethods();   
            for (int i = 0; i < methods.length; i++) {   
                if (methods[i].getName().startsWith("get")) {   
                    Object retobj = methods[i].invoke(tfpt, null);   
                    System.out.println(methods[i].getName() + "="  
                            + (String) retobj);   
                }   
            }   
        } catch (ClassNotFoundException e) {   
            e.printStackTrace();   
        } catch (IllegalArgumentException e) {   
            e.printStackTrace();   
        } catch (IllegalAccessException e) {   
            e.printStackTrace();   
        } catch (InvocationTargetException e) {   
            e.printStackTrace();   
        }   
    }   
}  
相关标签: 错误总结