简体   繁体   English

HashMap可以用值的类名推断键名

[英]HashMap that can infer key name with name of value's class

Is there something out there, maybe Guava, that could infer the key name of a HashMap from the either the classname or variable name of the key value? 是否有某些东西(也许是Guava)可以从键值的类名或变量名推断HashMap的键名? Like: 喜欢:

public Class MyBean {
   //basic properties, getters, setters, etc.
}

MyBean myBean = new MyBean();
Map<String, Object> myHashMap = new HashMap<String, Object>();
myHashMap.put(myBean);
System.out.println(myHashMap.get("myBean"));

It would be impossible to do from the variable name - because by the time the value of the variable has been passed to the put method, the variable name is effectively lost. 用变量名是不可能的-因为当变量的传递到put方法时,变量名实际上已经丢失了。 There can be multiple variables referring to the same object, or no variable: 可以有多个变量引用同一对象,或者没有变量:

myHashMap.put(new SomeOtherBean()); // What key would be used?

It would be easy to do it by class name, but that would have a pretty limited utility, I suspect. 通过类名来完成它很容易,但是我怀疑它的实用程序非常有限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我们将自定义类对象作为键和值传递时,如何根据键名从HashMap获取值 - How to get value from HashMap depending on key name, while we are passing custom class objects as key and value 根据键名从 HashMap 获取字符串值 - get string value from HashMap depending on key name Hashmap 使用哪个键和值来搜索姓名和电话号码 - Hashmap using which key and value to search name and phonenumber 如何使用JPA为Hashmap的值设置列名? - How to set column name for Hashmap's value with JPA? 为什么 Kotlin 不能用可空值类型推断此 HashMap 的类型? - Why can't Kotlin infer the type for this HashMap with a nullable value type? 什么是内部springframework类(ses),它采用属性名称和字符串值,推断类型并在bean上设置它? - What is the internal springframework class(ses) that take a property name and string value, infer the type and set it on a bean? 我可以使用Value的属性之一作为HashMap中的键吗<Key, Value> - Can I use one of Value's properties as a Key in a HashMap<Key, Value> 我可以声明一个HashMap吗 <key> 而不是HashMap <key,value> ? - Can I declare a HashMap<key> instead of a HashMap<key,value>? 如何从类中的值更新HashMap键? - How to update HashMap key from value in a class? 将HashMap的键和值连接到列表 - Connect a HashMap's key and value to a list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM