主函数:
import java.lang.reflect.Field; public class reflec { public static void main(String[] args) throws NoSuchMethodException, ClassNotFoundException, IllegalAccessException { TestClassEx t = new TestClassEx(); while(t!=null) { for (Field f : t.getClass().getDeclaredFields()) {
//对于private的属性,如果不解锁,那么将无法访问,会报错 f.setAccessible(true); Object value = f.get(t); System.out.println(f.getName() + ":" + value); } } } }
实体类:
class TestClassEx{ private String leijun = "are you ok?"; }
运行结果:
leijun:are you ok?
Process finished with exit code 0