Alex Rivera | Logout

Redundant generic parameters

Asked 2012-03-13T12:47:17.143
9

I have this two interfaces and classes:

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

public interface GenericRepository<T extends Identifiable<K>, K> {
    T get(K id);
}

public class MyEntity implements Identifiable<Long> {

    private Long id;

    public Long getId() {
        return id;
    }
}

public class MyService {
    private GenericRepository<MyEntity, Long> myEntityRepository;
}

It all works as desired. But in my opinion second generic parameter in GenericRepository (K) is redundant. Because I know that MyEntity is an Identifiable, I think it would be great if I can finally use it like this:

public class MyService {
    private GenericRepository<MyEntity> myEntityRepository;
}

But I'm trying different things without succeeding. Is it possible? If not, why not?

UPDATE: Answering some responses. I think compiler knows something about which type is the generic in MyEntity. For example:

public class MyEntityGenericRepository implements GenericRepository<MyEntity, Long> {
    // compiles...
}

public class MyEntityGenericRepository implements GenericRepository<MyEntity, String> {
    // compiler says: "Bound mismatch: The type MyEntity is not a valid substitute for the bounded parameter <T extends Identifiable<K>> of the type GenericRepository<T,K>"
}
Edit
Report

1 Answer

1

Not much you can do, other than introduce an interface that just refines GenericRepository

  public interface LongKeyedRepository<T extends Identifiable<Long>> 
        extends GenericRepository<T, Long> { {
  //No new methods need to be defined
  }

Then you can have

private LongKeyedRepository<MyEntity> myEntityRepository;

etc.

answered 2012-03-13T13:15:56.417

Your Answer