これは、リフェクションを使用して実行できます。
Field field = Record.class.getField(fieldToUse);
Object fieldValue = field.get(record);
完全な例:
static class Record {
public String name;
public int age;
public Record(String name, int age) {
this.name = name;
this.age = age;
}
}
public static void main(String[] args) throws Exception {
Record[] records = new Record[2];
records[0] = new Record("David", 29);
records[1] = new Record("Andreas", 28);
System.out.println("Davids name: " + getField("name", records[0]));
System.out.println("Andreas age: " + getField("age", records[1]));
}
private static Object getField(String field, Record record) throws Exception {
return record.getClass().getField(field).get(record);
}
プリント:
Davids name: David
Andreas age: 28