Search code examples
javagenericstype-parameter

How to define a type parameter inside a type parameter in java generics


I have a message dto

class MyMessage<T>{
  T payload;
  String groupId;
}    

I have an interface that has a simple implementation

interface Sender<T>{
    void sendMessage(T message);
}

class SenderService implements Sender<MyMessage>{
    @Override
    public void sendMessage(MyMessage message){...}
}

Now here MyMessage has a raw type and I want MyMessage to have a type paramter also which will define my payload dynamically. How to achieve it? I have tried the following.

class SenderService implements Sender<MyMessage>{
    @Override
    public <E> void sendMessage(MyMessage<E> message){...}
}

But it gives compilation error as the method is not overriden correctly. What I need to change in my abstract interface method to make it work?


Solution

  • Sender.sendMessage isn't a generic method: you can't add a new type variable on an implementation of that method:

    class SenderService implements Sender<MyMessage<String>>{
        @Override
        public void sendMessage(MyMessage<String> message){...}
    }
    

    If you want a SenderService that sends MyMessages of any type type, make it implement a wildcarded type:

    class SenderService implements Sender<MyMessage<?>>{
        @Override
        public void sendMessage(MyMessage<?> message){...}
    }
    

    If you want a SenderService that sends MyMessages of a particular type, make SenderService generic:

    class SenderService<E> implements Sender<MyMessage<E>>{
        @Override
        public void sendMessage(MyMessage<E> message){...}
    }