Bojan Vukasovic
Bojan Vukasovic

Reputation: 2268

Generics specific interface definition in Java

Is it possible to define following in Java:

public interface IGenericRepo<T> {
    void add();
    void delete();
    void attach();
}

public interface IGenericRepo<Book> {
    default String bookSpecificMethod(){
      return "smthn";
    }
}

public class NHGenericRepo<T> implements IGenericRepo<T>{
    /* implementation */
}

public class NHUnitOfWork implements UnitOfWork{
    @Autowired
    public void setBookRepo(NHGenericRepo<Book> bookRepo) {
        this.bookRepo= bookRepo;
    }
    public NHGenericRepo<Book> getBookRepo() {
       return bookRepo;
    }
    private NHGenericRepo<Book> bookRepo;
}

And to be able somewhere in code to have:

{
    @Autowired
    public void setNhuw(NHUnitOfWork nhuw) {
        this.nhuw = nhuw;
    }

    private NHUnitOfWork nhuw;

    /**/

    {
        String st = this.nhuw.getBookRepo().bookSpecificMethod();
    }
}

In .net this is possible by using Extension Method with "this IGenericRepo<Book>" as a first method parameter.

Upvotes: 2

Views: 78

Answers (1)

Tim B
Tim B

Reputation: 41168

The closest you can come is:

public interface IBookGenericRepo extends IGenericRepo<Book> {
    void BookSpecificMethod();
}

Upvotes: 5

Related Questions