0

所以我有一个抽象实体Compound和一个抽象 Service CompoundService<T extends Compound>

还有另一个服务类需要访问CompoundService<T extends Compound>(任意数字,编译时未知的实现)的任何实现。这在 1 个特定方法中是必需的,并且该方法可以采用类参数Class<? extends Compound>

问题是我如何类型安全地将此类映射到相应的服务类?

类似的东西Map<Class<? extends Compound>, CompoundService<? extends Compound>>不起作用,因为我需要通用参数CompoundService是特定的而不是通配符。

我不确定如何解释这一点。但compoundService.getById(compoundId)返回 type 的Compound实例TcompoundService.save(compound)需要compoundtype T。这意味着

Map<Class<? extends Compound>, CompoundService<? extends Compound>> services = //...;
CompoundService<T> compoundService = services.get(compoundClass);

不起作用,因为 CompoundService<? extends Compound>>不能强制转换为CompoundService<T>.

嗯,不确定这是否有帮助。问题是 Class 对象Class<? extends Compound>到这个“类型”服务类的映射CompoundService<? extends Compound>

有什么想法可以实现这一目标吗?

4

1 回答 1

1

我相信这是你想要做的:

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);
    }

}

我认为您不会比这更好并避免由于类型擦除而导致的演员表

于 2013-03-27T21:13:06.057 回答