2012年3月28日水曜日

Java/リフレクションメモ その1


対象クラスの全てのフィールド(privateを除く)名称と値を取得して、Mapリストに詰めて返却する機能。

* 利用側

List<Map<String, Text>> testMapList = LogText.getFieldsMapList();
if (testMapList == null) {
 return;
}

MapReduce mapReduce = new MapReduce();
int index = 1;

for (Map<String, Text> map : testMapList) {
 String fieldName = TestUtil.getCutSquareBracketKeyString(map);
 Text text = (Text) map.get(fieldName);
 
 try {
  mapReduce.map(null, text, null, null);
 } catch (Exception e) {
  e.printStackTrace();
 }
}
* API

public static List<Map<String, Text>> getFieldsMapList() throws Exception {
 Field[] fields = TestLogText.class.getDeclaredFields();
 List<Map<String, Text>> textLinkedList = new LinkedList<Map<String, Text>>();
 for (Field field : fields) {
  HashMap<String, Text> map = new HashMap<String, Text>();
  Text text = new Text(field.get(field.getName()).toString());
  map.put(field.getName(), text);
  textLinkedList.add(map);
 }
 return textLinkedList;
}