---
title: "利用反射遍历一个POJO对象的各个字段名及属性。。。"
author: "wangshu3000"
date: "2007-12-12T10:54:26Z"
tags: []
slug: "pojo"
draft: false
lastmod: "2007-12-12T10:54:26Z"
id: 147738
url: "https://mid.iteye.com/blog/147738"
---

java 代码

01. public class ReflectionFiledPrintTest {
02. private String name = "GoGoGo";
03. private String city = "DoDoDo";
04. public String getCity() {
05. return city;
06. }
07. public void setCity(String city) {
08. this.city = city;
09. }
10. public String getName() {
11. return name;
12. }
13. public void setName(String name) {
14. this.name = name;
15. }
16. public static void main(String args\[]) {
17. Object obj = "222";
18. System.out.println("111"+obj);
19. ReflectionFiledPrintTest tfpt = new ReflectionFiledPrintTest();
20. try {
21. Class reClass = Class
22. .forName("reflection.ReflectionFiledPrintTest");
23. Method methods\[] = reClass.getDeclaredMethods();
24. for (int i = 0; i &lt; methods.length; i++) {
25. if (methods\[i].getName().startsWith("get")) {
26. Object retobj = methods\[i].invoke(tfpt, null);
27. System.out.println(methods\[i].getName() + "="
28. + (String) retobj);
29. }
30. }
31. } catch (ClassNotFoundException e) {
32. e.printStackTrace();
33. } catch (IllegalArgumentException e) {
34. e.printStackTrace();
35. } catch (IllegalAccessException e) {
36. e.printStackTrace();
37. } catch (InvocationTargetException e) {
38. e.printStackTrace();
39. }
40. }
41. }