通过反射,可以获取所有声明的成员变量(包括所有的),代码如下:

package spt.test.src;

public class Person {
	private String name = "pri_name";
	public String id;
}

 运行测试:

package spt.test;

import java.lang.reflect.Field;

import spt.test.src.Person;

class ReflectionTest {
	@SuppressWarnings("unchecked")
	public static void main(String[] args) throws IllegalAccessException {
		Person person = new Person();
		person.id = "akk";
		
		Class<Person> pClass = (Class<Person>) person.getClass();
		for (Field field : pClass.getDeclaredFields()) {
			try {
				//set accessable.
				field.setAccessible(true);
				//get field name and value.
				System.out.println(field.getName() + ":" + field.get(person));
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			}
		}
	}
}

 将在控制台上输出:

name:pri_name
id:akk