我有一个类型为Records []的数组,其中包含名称,年龄和分数等字段.
我有一个方法将需要访问这些字段之一,但我不知道哪个.
例如,我想做以下事情:
String fieldToUse = "name";
System.out.println(myRecords[0].fieldToUse);
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我可以将fieldToUse切换到我想要找到的任何字段.但这不起作用 - 我该怎么做?
提前致谢.
编辑:myRecords的类型为Records.
这可以使用反射来完成:
Field field = Record.class.getField(fieldToUse);
Object fieldValue = field.get(record);
Run Code Online (Sandbox Code Playgroud)
完整示例:
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);
}
Run Code Online (Sandbox Code Playgroud)
打印:
Davids name: David
Andreas age: 28
Run Code Online (Sandbox Code Playgroud)