通过反射获取对象的值

public static void main(String[] args) {
		Day day= new Day();
		  day.setDay01a(111);
		  day.setDay01b(1);
	        day.setDay02a(2);
	        day.setDay02b(3);
	        day.setDay03a(4);
	        day.setDay03b(5);
	        Field[] declaredFields = day.getClass().getDeclaredFields();
	        try {
	            for (Field field : declaredFields) {
	                //字段名称
	                String name = field.getName();
	                if (name.equals("day02a")) {
	                    //用于获取private成员变量
	                    field.setAccessible(true);
	                    System.out.println(name);
	                    //字段值
	                    Object o = field.get(day);
	                    System.out.println(o);
	                }
	            }
	        } catch (IllegalAccessException e) {
	            e.printStackTrace();
	        }
	
	        
	}

实体类:

 private int day01a;
	    private int day01b;
	    private int day02a;
	    private int day02b;
	    private int day03a;
	    private int day03b;
//省去get和set方法

 

你可能感兴趣的:(代码)