@ghimi
2018-08-09T06:32:52.000000Z
字数 1392
阅读 784
未分类
public class Test01 {private static String value1 = "private static value1";public static String value2 = "public static value2";private String value3 = "private value3";public String value4 = "public value4";public String value5 = "public value5";public static void main(String[] args) {Test01 test01 = new Test01();Field[] declaredFields = test01.getClass().getDeclaredFields();for (Field field : declaredFields) {try {// 显示所有被声明的变量(包括私有变量和类变量)的值,如果为非法访问则报异常System.out.println("declaredFields : " + "\tname : "+field.getName() + "\tmodifiers : "+ Modifier.toString(field.getModifiers())+ "\tvalue : "+field.get(test01));} catch (IllegalArgumentException | IllegalAccessException e) {e.printStackTrace();}}Field[] fields = test01.getClass().getFields();for (Field field : fields) {try {//显示所有类中可以被正常访问的 (accessible public fields of the class) public 字段,如果为非法访问则报异常System.out.println("Fields : " + "\tname : "+field.getName() + "\tmodifiers : "+Modifier.toString(field.getModifiers()) + "\tvalue : "+field.get(test01));} catch (IllegalArgumentException | IllegalAccessException e) {e.printStackTrace();}}}//循环检查私有成员变量是否为空,只要有一个私有成员变量为空则返回falsepublic boolean checkRequired() {Field[] declaredFields = this.getClass().getDeclaredFields();for (Field field : declaredFields) {if(Modifier.isPrivate(field.getModifiers()) && !Modifier.isStatic(field.getModifiers())){try {if(field.get(this) == null)return false;} catch (IllegalArgumentException | IllegalAccessException e) {return false;}}}return true;}}