satishkk
satishkk

Reputation: 63

Java interface with generics with bounded parameter

I have a requirement where I need to use generics as client can use their desired datatype when using my service. The code looks like:

public interface MyService<T extends Base> {

    void meth1(T type);
}

@Service("abc")
public class MyServiceImpl<T> implements MyService<T extends Base> {

    @Override
    public void meth1(T type) {
    }
}

where Base is a abstract class. the clients will use a subclass of it to call this service.

public abstract class Base {
}

Issue: The implementation class(MyServiceImpl) doesn't compile. I am not sure about the problem here.

Clients will use this service and push their datatypes which is subclass of Base. e.g something like this:

    @Autowired
    @Qualifier("abc")
    private MyService<xx> service;


service.meth1(xx)  //where xx is subclass of Base

Am I doing something fundamentally wrong here. Please suggest.

Upvotes: 1

Views: 1955

Answers (1)

Eran
Eran

Reputation: 393791

The type bound should be in the declaration of the type parameter:

public class MyServiceImpl<T extends Base> implements MyService<T>

Upvotes: 3

Related Questions