如何通过类类型创建泛型类型安全的HashMap? [英] How to create a generic typesafe HashMap by class type?

查看:46
本文介绍了如何通过类类型创建泛型类型安全的HashMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个HashMap,它将特定的类类型映射到一个特定的新对象.

I'd like to create a HashMap that maps specific class types to one single specific new object.

稍后,我想传递类类型并获取对该特定对象的引用. 简单的例子:

Later I want to pass the class type and get the reference to that specific object. Simple example:

Map<Class<?>, ?> values = new HashMap<>();

public <T> t get(Class<T> type) {
    return values.get(type);
}


//pet and car do not share any interface or parent class
class Pet;
class Car;

//error: not applicable for arguments
values.put(Pet.class, new Pet());
values.put(Car.class, new Car());

用法:

values.get(Pet.class);

我如何相应地创建这样的通用哈希图和查找功能?

How can I create such a generic hashmap and lookup function accordingly?

推荐答案

如果您希望能够将其他内容作为Object放置在地图中,则需要存储 some 类型的对象,因此从此开始:

You need to store some type of object, if you want to be able to put anything else as Object in the map, so start off with this:

Map<Class<?>, Object> values = new HashMap<>();

必须这样做,因为对于地图存储的类型,?不是具体对象,而Object是.

This has to be done this way, because ? is not a concrete object, but Object is, for the type the map stores.

因此以下代码段可以正常运行,而不会发出警告:

So the following snippet works, without warnings:

Map<Class<?>, Object> values = new HashMap<>();
values.put(Pet.class, new Pet());
values.put(Car.class, new Car());

现在的诀窍是获取对象,我们按如下操作:

Now the trick is to get objects, we do it as follows:

@SuppressWarnings("unchecked")
private <T> T get(Class<T> clazz) {
    return (T)values.get(clazz);
}

现在您的目标是为了确保地图包含在运行时不提供任何错误的对.如果将new Car()实例与Car.class放置在一起,那么将会出错.

Now your goal is to ensure that the map contains pairs that provide no errors on runtime. If you put a new Car() instance with Car.class , then you are going to get errors.

下面是示例代码:

    values = new HashMap<>();
    values.put(Pet.class, new Pet());
    values.put(Car.class, new Car());

    System.out.println("get(Pet.class).getClass() = " + get(Pet.class).getClass());
    System.out.println("get(Car.class).getClass() = " + get(Car.class).getClass());

将打印:

get(Pet.class).getClass() = class testproject8.Pet
get(Car.class).getClass() = class testproject8.Car

这篇关于如何通过类类型创建泛型类型安全的HashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆