以前一直不知道反射到底能用在哪裏,直到我看到了公司OA的考勤表設計:
DAY表示每一個月的天數,後面的數字表示每個月的幾號,A表示上午,B表示下午。好比DAY01A用以表示當月1號的出勤狀況。
因此,這個表用以記錄考勤數據的字段共有62個。。。
後來想用這個天天考勤數據,才發現反射真是個好東西。
以三天數據爲例:java
{ "day01a":0, "day01b":1, "day02a":2, "day02b":3, "day03a":4, "day03b":5 }
若是要獲取day02b字段的值:web
public class OaTest { public static void main(String[] args) { Day day = new Day(); day.setDay01a(0); day.setDay01b(1); day.setDay02a(2); day.setDay02b(3); day.setDay03a(4); day.setDay03b(5); //如今要獲取字段day02b的值 Field[] declaredFields = day.getClass().getDeclaredFields(); try { for (Field field : declaredFields) { //字段名稱 String name = field.getName(); if (name.equals("day02b")) { //用於獲取private成員變量 field.setAccessible(true); System.out.println("字段名稱:" + name); //字段值 Object o = field.get(day); System.out.println("要獲取字段的值:" + o); } } } catch (IllegalAccessException e) { e.printStackTrace(); } } } //對應表實體 class Day { private int day01a; private int day01b; private int day02a; private int day02b; private int day03a; private int day03b; //省略get,set方法 }
執行結果:json
字段名稱:day02b
要獲取字段的值:3
因此要獲取目標字段值,只須要經過日期拼接成所需字段的名稱,而後經過上面方法進行字段值獲取便可。svg