[英]Java - Define HashMap type with a method argument
I want a method argument to define the class a HashMap will accept. 我想要一个方法参数来定义HashMap将接受的类。 Something along the lines of: 类似于以下内容:
private HashMap hashMap = new HashMap();
public boolean createMap(Object obj) {
return hashMap = new HashMap<String, obj.getClass()>() != null;
}
You can't do what you're trying to do: you can't "define the class a HashMap
will accept" because at runtime a HashMap
will accept all classes. 您无法做您想做的事情:您不能“定义HashMap
可以接受的类”,因为在运行时HashMap
可以接受所有类。
What you could do, on the other hand, is: 另一方面,您可以做的是:
private Map<String, ?> map;
public <V> void createMap(Class<V> clazz) {
map = Collections.checkedMap(new HashMap<String, V>(),
String.class, clazz);
}
...which will actually enforce the restrictions you're trying to create, with reflection. ...实际上将通过反射来强制实施您要创建的限制。 In this case, your hashMap
member should have type Map<String, Object>
, though it will enforce 在这种情况下,您的hashMap
成员应具有Map<String, Object>
,尽管它将强制执行
define a typed function that accepts the type you desire as value for the map 定义一个接受您想要的类型作为地图值的类型化函数
public <T> Map<String, T> checkedStringKeyMap(Class<T> type) {
return Collections.checkedMap(new HashMap<String, T>(), String.class, type);
}
then create your map as follows 然后如下创建地图
Map<String, Person> persons = checkedStringKeyMap(Person.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.