Java泛型如何转换为子类型以调用泛型方法

Java泛型如何转换为子类型以调用泛型方法,java,generics,java-8,Java,Generics,Java 8,我有以下界面: public interface EntityCloneService<T extends AbstractNamedEntityBase> { /** * Given a UUID load the Entity Type. * * @param uuid * @return Entity From DB and */ public T getByUuid(UUID uuid); /** * Given the Existi

我有以下界面:

public interface EntityCloneService<T extends AbstractNamedEntityBase> {

 /**
  * Given a UUID load the Entity Type.
  * 
  * @param uuid
  * @return  Entity From DB and 
  */
 public T getByUuid(UUID uuid);


 /**
  * Given the Existing Entity,  clone it and save in DB, then return clone instance.
  */
 public T getCloneAndSave(T existingEntity) throws Exception;

}
公共接口EntityCloneService{
/**
*给定UUID加载实体类型。
* 
*@param-uuid
*@returnentityfromdb和
*/
公共T getByUuid(UUID-UUID);
/**
*给定现有实体,克隆它并保存在数据库中,然后返回克隆实例。
*/
公共T getCloneAndSave(T existingEntity)抛出异常;
}
现在我有了通用服务,我有

@Component
public class GenericEntityCloneService {

    private static final Map<String,EntityCloneService<? extends AbstractNamedEntityBase>> registration = 
            new HashMap<String,EntityCloneService<? extends AbstractNamedEntityBase>>(); // here we have registration of all entity by name to service actual implementation.

    public void clone(AbstractNamedEntityBase existingEntity) {
        EntityCloneService<? extends AbstractNamedEntityBase> service = registration.get("SOME KEY");
        AbstractNamedEntityBase  entity =   service.getByUuid(ref.getUuid());  // THIS WORKS because it up casting.

        service.getCloneAndSave(entity);    // now how do I pass entity object such that 
    }
}
@组件
公共类通用实体克隆服务{

私有静态最终映射这里您使用
T
作为生产者和消费者,因此您不能在这里使用有界类型参数。您必须像这样使用方法级泛型

public <S> S getCloneAndSave(S existingEntity) throws Exception;
public的getCloneAndSave(S existingEntity)抛出异常;
问题在于:

AbstractNamedEntityBase entity = service.getByUuid(ref.getUuid());
该行丢弃
T
。每个EntityCloneService只使用AbstractNamedEntityBase的一个子类。该服务的getCloneAndSave方法需要类型为
T
的对象,该对象是AbstractNamedEntityBase的某个特定子类


没有办法在映射中保留值的泛型类型。您所知道的只是它是一个与
EntityCloneService相关的,因为您不知道特定
EntityCloneService
实现的实际类型参数,所以不可能以类型安全的方式执行。这将编译,但是EntityCloneService应该使用T实例,而不仅仅是任何可能的类型。
default T getCloneAndSaveFor(UUID uuid)
throws Exception {
    T entity = getByUuid(uuid);
    return getCloneAndSave(entity);
}
private <E extends AbstractNamedEntityBase> E getCloneAndSaveFor(
    UUID uuid,
    EntityCloneService<E> service)
throws Exception {

    E entity = service.getByUuid(uuid);
    return service.getCloneAndSave(entity);
}