如何使用其关键字和值属于某个层次结构的通用地图? [英] How to work with a generic map whose key and values belong to a certain hierarchy?

查看:95
本文介绍了如何使用其关键字和值属于某个层次结构的通用地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是创建一个Map,其键是Class实例,其值是相应类的实例。意义,

My objective is to create a Map whose keys are Class instances and whose values are instances of the corresponding Class. Meaning,

映射(层次结构中的某个类 - >其对应的实例)

Map (a certain class in a hierarchy --> its corresponding instance)

要做到我宣布地图像

Map<Class<? extends BaseService>, ? extends BaseService> serviceMap = 
    new HashMap<Class<? extends BaseService>, BaseService>();
//Assume BaseService is at the root of hierarchy.

上述编译。

按顺序填写地图,我使用

In order to populate the Map, I used

public <T extends BaseService> void register(T service) {   
    serviceMap.put(service.getClass(), service);    
}

这不编译。

我该如何使这项工作?为什么不编译?

How do I make this work ? And why doesn't this compile ?

推荐答案

您使用通配符与您的英文定义不完全一致。当您定义:

Your use of wildcards isn't exactly consistent with your English definition. When you define:

Map<Class<? extends BaseService>, ? extends BaseService> serviceMap;

这可能被描述为 serviceMap 来自Classes的地图,它将 BaseService 扩展到某些类型的价值(即$ code> BaseService 或一个子类)。

this might be described as "serviceMap is a map from Classes which extend BaseService, to some type of value (which is BaseService or a subclass)".

编译器在此上下文中拒绝您的注册方法是正确的。 serviceMap 的值类型被声明为简单的东西 - 所以你可以轻松地分配一个地图,值类型为 ServiceImplOne 。您的注册方法可以使用类 ServiceImplTwo 的参数调用。您不能将其插入到地图中,因为它与通用参数不一致!

The compiler is correct to reject your register method in this context. serviceMap's value type is declared to be simply "something" - so you could easily assign a map to it with a value type of ServiceImplOne. And your register method could be called with an argument of class ServiceImplTwo. You can't insert this into the map as it's not consistent with the generic parameters!

很明显,由于您希望能够插入任何类型的服务,地图必须接受 BaseService 的所有实例,而不是基于BaseService的(未知)子类型。因此,您可以通过使用具体值类型声明地图来解决此问题:

It's clear that since you want to be able to insert any type of service, the map must accept all instances of BaseService as values, not some (unknown) subtype of BaseService. Therefore you can fix this by declaring the map with a concrete value type:

Map<Class<? extends BaseService>, BaseService> serviceMap;

这篇关于如何使用其关键字和值属于某个层次结构的通用地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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