繁体   English   中英

接口中的泛型类型和多态性

[英]Generic types and polymorphism in interfaces

我正在尝试使用MyBatis生成对DB的一些调用,但是到目前为止,我遇到了麻烦。

假设我有以下实体和映射器:

public interface Entity {

    <T extends Entity> Class<Insertable<T>> mapper();
}

public interface Insertable<T extends Entity> {

    void insert(T entity);
}

public interface ClientMapper extends Insertable<Client> {

    void insert(Client client);
}

public interface CampaignMapper extends Insertable<Campaign> {

    void insert(Campaign campaign);
}

public class Client implements Entity {

    private final Long id;

    public Client(final Long id) {
        this.id = id;
    }

    @Override
    public <T extends Entity> Class<Insertable<T>> mapper() {
        return ClientMapper.class; // Incompatible types error
    }

我得到即使这个编译错误ClientMapper的类型是Insertable<Client> ,是Client类型的Entity

目的是获得以下类型安全的代码:

public class MapperOperation {

    public static void insert(Entity entity) {
        insert(entity, entity.mapper());
    }

    private static <V extends Entity, K extends Insertable<V>> void insert(V entity, Class<K> mapperClass) {
        try (SqlSession session = PersistenceManager.get().openSession()) {
            K mapper = session.getMapper(mapperClass);
            mapper.insert(entity);
            session.commit();
        } catch (Exception e) {
            log.error("Could not insert entity {}", entity, e);
        }
    }
}

这样,我可以使用任何Entity的实例调用方法insert ,然后要求他给我他的mapper以便我可以插入它。

这可能吗? 难道我做错了什么?

它应与以下更改一起编译:

public interface Entity {
    <T extends Entity> Class<? extends Insertable<T>> mapper();
}    

// ...

public <T extends Entity> Class<? extends Insertable<T>> mapper() {
    return ClientMapper.class;
}

不能将Class<ClientMapper>分配给Class<ClientMapper> Class<Insertable<T>> ,出于相同的原因,也不能将List<Integer>分配给List<Number>

如果可以,那将是不安全的:

List<Integer> li = new ArrayList<>();
List<Number> ln = li; // does not compile
ln.add(3.14);
Integer i = li.get(0); // it's a Double!

编辑:这不是唯一的问题:该方法返回的内容取决于T ,但是您返回了另一个。 这个问题可以简化:

class A {}
class B extends A {}
class C extends A {}

<T extends A> T getValue() {
    return new C();
}

在这里, T可能被解析为A任何子类型,因此我们无法返回C的实例,因为T可能被解析为B (例如,通过调用this.<B>getValue() ),并且C不是B的子类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM