java - 在未知类型的对象上使用字段
问题描述
我的应用程序构建了一个Field
's 的缓存,稍后将在其生命周期内访问该缓存。我认为创建Field
's 的索引会比每次需要访问Field
. 不过,无论如何我都没有看到Field
在 Java 对象上使用。
POJO:
public class Employee {
private String firstName;
private String lastName;
Employee(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
例子:
public static void main(String[] args) throws IOException {
Map<String, Field> fields = new HashMap<>();
for (Field field : Employee.class.getDeclaredFields()) {
fields.add(field.getName(), field);
}
Object employee = new Employee("bob", "saget");
fields.entrySet().forEach((entry) -> {
// Showing intent, obviously getFieldValue doesn't exist
System.out.println("Field " + entry.getKey() + ": " + employee.getClass().getFieldValue(entry.getValue());
});
}
预期输出:
Field firstName: bob
Field lastName: saget
解决方案
推荐阅读
- r - 在根据条件将一个 data.frame 的值添加到另一个时保留行顺序
- python - 在 Pandas Dataframe 中查找和替换各种子字符串
- r - 连续不适用的次数
- python - 如何在 Pandas 和 Jupyter Notebook 中创建带有指向本地文件的可单击超链接的表
- html - 我想在 asp.net 的下拉列表旁边放一个按钮
- google-apps-script - 获取电子表格的 ID
- recursion - 不知道为什么 let 函数没有正确返回 sbcl lisp 中的值
- python - pandas.Series.str.replace() 基于另一个系列
- oop - D中类的比较运算符重载?
- android - 如何在 Room @Query 中使用参数字段?