因此,我有一个抽象实体Compound
和一个抽象服务CompoundService<T extends Compound>
。
还有另一个服务类,需要访问CompoundService<T extends Compound>
的任何实现(任意数字,在编译时未知的实现)。这是1个特定方法所必需的,并且该方法可以使用类参数Class<? extends Compound>
。
问题是如何将此类安全地映射到相应的服务类?
像Map<Class<? extends Compound>, CompoundService<? extends Compound>>
之类的东西不起作用,因为我要求CompoundService
的通用参数是特定的而不是通配符。
我不确定如何解释这一点。但是compoundService.getById(compoundId)
返回类型为Compound
的T
实例,或者compoundService.save(compound)
要求compound
类型为T
。这意味着
Map<Class<? extends Compound>, CompoundService<? extends Compound>> services = //...;
CompoundService<T> compoundService = services.get(compoundClass);
不起作用,因为不能将
CompoundService<? extends Compound>>
强制转换为CompoundService<T>
。嗯,不确定是否有帮助。问题是类对象
Class<? extends Compound>
到此“类型”服务类CompoundService<? extends Compound>
的映射。有什么想法可以实现这一目标吗?
最佳答案
我相信这是您想要做的:
abstract class Compound { }
class Compound1 extends Compound { }
abstract class CompoundService<T extends Compound> {
...
}
class Compound1Service extends CompoundService<Compound1> {
...
}
public class Test {
static Map<Class<? extends Compound>, CompoundService<? extends Compound>> serviceMap = new HashMap<Class<? extends Compound>, CompoundService<? extends Compound>>();
public static <T extends Compound> void main(String[] args) {
serviceMap.put(Compound1.class, new Compound1Service());
CompoundService<Compound1> service = getServiceFromMap(Compound1.class);
System.out.println(service.getClass());
}
public static <T extends Compound> CompoundService<T> getServiceFromMap(Class<T> clazz) {
return(CompoundService<T>)serviceMap.get(clazz);
}
}
我认为您不会比这更好,并且可以避免由于类型擦除而导致的类型转换