java - 如何从 List<> 中获取值,将 String 作为变量名
问题描述
我有一个基于数据库的列表。
List<Contact> contactList;
有很多变数。例如:
String name;
String phone;
我可以以这样的方式获得特定的价值吗?
String var = "name";
String val = contactList.get(0).var <--- this Sting variable here
有什么办法可以做这样的事情吗?我不想写 x10 :
if(var == "name"){
String val = contactList.get(0).name;
}
我认为这样做是可行的,但我是新手,如果我的问题有问题,我很抱歉。我将非常感谢您的帮助。
工作代码:
谢谢你的答案。如果将来有人要寻找答案,这是完整的代码:
private Map<String, Function<Contact, String>> map;
map = new HashMap<>();
map.put("Name", c -> c.name);
map.put("Phone", c -> c.phone);
map.put("Email", c -> c.email);
String some_val = map.get(second_value).apply(contactList.get(position));
解决方案
您需要一个Map<String, Function<Contact, String>>
包含方法引用,以属性名称为键。
例如:
// Construct this once, store in a static final field.
Map<String, Function<Contact, String> map =
Map.of("name", c -> c.name /* etc for other fields */);
// Then, when you want to get the value:
String val = map.get(var).apply(contactList.get(0));
推荐阅读
- docusignapi - Docusign api 通过多个信封持久化数据
- latex - Pandoc 从输入子文件夹加载图像但不加载乳胶文件
- python - 弱人工智能的模式识别只返回字典中的第一个响应
- node.js - 使用 node/js 的站点地图库生成的站点地图已损坏
- laravel - Livewire 错误:公共属性 [message] 的类型必须为:[numeric、string、array、null 或 boolean]
- jquery - Krajee Bootstrap 文件输入错误按钮删除
- javascript - Vue.component() 带加载器的动态导入
- java - 遵循安装指南后 Sakai 构建错误
- sql - 根据 1 列的信息创建 2 列
- pandas - 我需要帮助使用 pandas 在大电子表格上查找价格