本文介绍了具有受键类型参数限制的值的 Java 映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 中是否有一种方法可以将值的类型参数绑定到键的类型参数的映射?我想写的内容如下:

公共类 Foo {//这个声明不会编译 - 它应该是什么?私有静态 Map, T>默认值;//这两个方法就好了公共静态<T>void setDefaultValue(Class clazz, T value) {defaultValues.put(clazz, value);}公共静态<T>T getDefaultValue(Class clazz) {返回 defaultValues.get(clazz);}}

也就是说,我可以针对 Class 对象存储任何默认值,前提是该值的类型与 Class 对象的类型相匹配.我不明白为什么不允许这样做,因为我可以确保在设置/获取值时类型正确.

感谢 cletus 的回答.我实际上并不需要地图本身的类型参数,因为我可以确保获取/设置值的方法的一致性,即使这意味着使用一些稍微难看的强制转换.

解决方案

您不是在尝试实现 Joshua Bloch 的类型安全异构容器模式,是吗?基本上:

公共类收藏{私有映射,对象>收藏夹 =new HashMap, Object>();公共 <T>void setFavorite(Class klass, T thing) {收藏夹.放置(类,东西);}公共 <T>T getFavorite(Class klass) {返回 klass.cast(favorites.get(klass));}公共静态无效主(字符串 [] args){收藏夹 f = 新收藏夹();f.setFavorite(String.class, "Java");f.setFavorite(Integer.class, 0xcafebabe);String s = f.getFavorite(String.class);int i = f.getFavorite(Integer.class);}}

来自 Effective Java(第二版)本演示文稿.

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:

From Effective Java (2nd edition) and this presentation.

这篇关于具有受键类型参数限制的值的 Java 映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 03:16