具有受密钥类型参数限制的值的Java映射 [英] Java map with values limited by key's type parameter
问题描述
Java中有没有一种方法可以让一个值的类型参数绑定到一个键的类型参数上?我想写的东西如下所示:
public class Foo {
//此声明不会编译 - 它应该是什么?
private static Map< Class< T> ;, T>默认值;
//这两种方法都很好
public static< T> void setDefaultValue(Class< T> clazz,T value){
defaultValues.put(clazz,value);
}
public static< T> T getDefaultValue(Class< T> clazz){
return defaultValues.get(clazz);
$ / code $ / pre
也就是说,我可以存储任何默认值Class对象,只要该值的类型与Class对象的类型匹配即可。我不明白为什么这不应该被允许,因为我可以确保设置/获取值类型是正确的。
编辑:谢谢cletus为他的答案。我实际上并不需要地图上的类型参数,因为我可以确保get / set方法的一致性,即使这意味着使用一些稍微丑陋的转换。
h2_lin>解决方案
你不是试图实现Joshua Bloch的类型安全的异构容器模式吗?基本上:
public class Favorites {
private Map< Class<?> ;,对象> favorites =
new HashMap< Class<?>,Object>();
public< T> void setFavorite(Class< T> klass,T thing){
favorites.put(klass,thing);
}
public< T> T getFavorite(Class< T> klass){
return klass.cast(favorites.get(klass));
public static void main(String [] args){
Favorites f = new Favorites();
f.setFavorite(String.class,Java);
f.setFavorite(Integer.class,0xcafebabe);
String s = f.getFavorite(String.class);
int i = f.getFavorite(Integer.class);
Is there a way in Java to have a map where the type parameter of a value is tied to the type parameter of a key? What I want to write is something like the following:
public class Foo {
// This declaration won't compile - what should it be?
private static Map<Class<T>, T> defaultValues;
// These two methods are just fine
public static <T> void setDefaultValue(Class<T> clazz, T value) {
defaultValues.put(clazz, value);
}
public static <T> T getDefaultValue(Class<T> clazz) {
return defaultValues.get(clazz);
}
}
That is, I can store any default value against a Class object, provided the value's type matches that of the Class object. I don't see why this shouldn't be allowed since I can ensure when setting/getting values that the types are correct.
EDIT: Thanks to cletus for his answer. I don't actually need the type parameters on the map itself since I can ensure consistency in the methods which get/set values, even if it means using some slightly ugly casts.
You're not trying to implement Joshua Bloch's typesafe hetereogeneous container pattern are you? Basically:
public class Favorites { private Map<Class<?>, Object> favorites = new HashMap<Class<?>, Object>(); public <T> void setFavorite(Class<T> klass, T thing) { favorites.put(klass, thing); } public <T> T getFavorite(Class<T> klass) { return klass.cast(favorites.get(klass)); } public static void main(String[] args) { Favorites f = new Favorites(); f.setFavorite(String.class, "Java"); f.setFavorite(Integer.class, 0xcafebabe); String s = f.getFavorite(String.class); int i = f.getFavorite(Integer.class); } }
From Effective Java (2nd edition) and this presentation.
这篇关于具有受密钥类型参数限制的值的Java映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!