helion3
helion3

Reputation: 37361

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.

I'm trying to design a single Model interface so that anyone using my API can see what data is available. The problem is that the ID or primary key type varies. For example from mysql it'll be a Long and mongo uses ObjectId, etc.

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.

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.

The dog model interface:

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

The sql-specific dog model:

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

Upvotes: 0

Views: 55

Answers (1)

surendrapanday
surendrapanday

Reputation: 548

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.

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 > {}

Upvotes: 1

Related Questions