Search code examples
javagenericsjax-rsjersey-2.0

JAX-RS Bind implementation of generic type in ApplicationBinder


Is it possible to bind a class with type parameters in an implementation of an AbstractBinder?

Generic repository class
public class Repository<T>{ ... }

Service class

public class AccountService{  

     Repository<User> repository;  

     @Inject  
     public AccountService(Repository<User> repository){  
        this.repository = repository;
     }

}

Bind generic repository in binder

public class ApplicationBinder extends AbstractBinder {

@Override
protected void configure() {  
      bind(Repository<User,Long>).to(Repository<User,Long>.class); <=== not working!
}

Solution

  • You can use TypeLiteral

    Supports inline instantiation of objects that represent parameterized types with actual type parameters. An object that represents any parameterized type may be obtained by subclassing TypeLiteral.

    TypeLiteral<List<String>> stringListType = new TypeLiteral<List<String>>() {};
    

    And instead of bind, you would need to use bindAsContract(TypeLiteral), as there is not bind method that accepts a TypeLiteral[1].

    bindAsContract(new TypeLiteral<Repository<User, Long>>(){});
    

    [1] - See more in AbstractBinder docs.