如果对于反射的基本概念还不了解的请见上一帖子。本文仅谈fields的用法demo
/** * * @author Zen Johnny * */ package com.cpms.test; import java.lang.reflect.Field; import java.util.List; public class ReflectDemo { public static void reflect() { Person employee = new Person(); Class<Person> clazz = (Class<Person>) employee.getClass(); for(Field field : clazz.getDeclaredFields()) {//getDeclaredFields System.out.println(field + "【" + field.getName() + "】"); } System.out.println("**********************************************"); for(Field field : clazz.getFields()) {//getFields System.out.print(field + "【" + field.getName() + "】"); } System.out.println("**********************************************"); } public static void main(String args[]) { reflect(); } } class Person{ public String nickName;//public field private String realName; private int age; private List<String> friends; private double money; //no setter and getter public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public List<String> getFriends() { return friends; } public void setFriends(List<String> friends) { this.friends = friends; } @Override public String toString() { return "Person [nickName=" + nickName + ", realName=" + realName + ", age=" + age + ", friends=" + friends + ", money=" + money + "]"; } }
输出:
所有属性:
public java.lang.String com.cpms.test.Person.nickName【nickName】 private java.lang.String com.cpms.test.Person.realName【realName】 private int com.cpms.test.Person.age【age】 private java.util.List com.cpms.test.Person.friends【friends】 private double com.cpms.test.Person.money【money】(无set个get的属性) ********************************************** 公共属性:
public java.lang.String com.cpms.test.Person.nickName【nickName】 **********************************************