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? 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. 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.
精彩评论