简体   繁体   English

Java 接口泛型,其中实现类定义类型

[英]Java interface generics where implementing classes define the type

I'm trying to design some interfaces for a library that will support multiple storage systems for it's data - like mysql, or mongo.我正在尝试为一个库设计一些接口,该接口将支持其数据的多个存储系统 - 如 mysql 或 mongo。

I'm trying to design a single Model interface so that anyone using my API can see what data is available.我正在尝试设计一个单一的Model接口,以便使用我的 API 的任何人都可以看到哪些数据可用。 The problem is that the ID or primary key type varies.问题是ID或主键类型不同。 For example from mysql it'll be a Long and mongo uses ObjectId, etc.例如从 mysql 它将是一个Long并且 mongo 使用 ObjectId 等。

I was thinking I could handle this with generics, but I'm not sure this is the right approach.我想我可以用泛型来处理这个问题,但我不确定这是正确的方法。 I don't want to have to cast all the time to get the right ID types.我不想一直强制转换以获得正确的 ID 类型。

Is this an acceptable approach or should I be using something else?这是一种可以接受的方法还是我应该使用其他方法? I don't want to build my APIs with this approach and then run into issues and have to redo it all.我不想用这种方法构建我的 API,然后遇到问题而不得不重做这一切。

The dog model interface:狗模型界面:

public interface DogModel<T> {
    T getId();
}

The sql-specific dog model: sql特定的狗模型:

public class SqlDogModel implements DogModel<Long> {
    private final Long id;

    public SqlDogModel(Long id) {
        this.id = id;
    }

    public Long getId() {
        return id;
    }
}

How I declare the model in the general storage interface:我如何在通用存储接口中声明模型:

public interface StorageAdapter {
    Optional<DogModel> getDog(String name);
}

It can be made simpler: An abstract class can implement an interface, but in my example I have the getter and setter logic in the base class and this can't happen in the interface as interfaces don't have logic.它可以变得更简单:抽象类可以实现接口,但在我的示例中,我在基类中有 getter 和 setter 逻辑,这不能在接口中发生,因为接口没有逻辑。

public abstract class DogModel < T > {
T id;
public T getId() {
    return id;
}
public void setId(T id) {
    this.id = id;
}}

public class SqlDogModel extends DogModel < Long > {}

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

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