【问题标题】:How to get value from List<> giving String as variable name [duplicate]如何从 List<> 中获取值,将 String 作为变量名 [重复]
【发布时间】:2021-09-15 08:10:59
【问题描述】:

我有一个基于数据库的列表。

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));

【问题讨论】:

  • 您还应该学习基本的 Java。这不是你在 Java 中比较字符串(或任何类型的对象)值的方式
  • 顺便说一句,不要调用变量var。它现在是一种关键字,可能会被读者误解。

标签: java android list


【解决方案1】:

您需要一个包含方法引用的Map&lt;String, Function&lt;Contact, String&gt;&gt;,以属性名称为键。

例如:

// 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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-23
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多