Clean code
Clean code

Reputation: 63

Different method parameter using generic from the interface parameter that implements it

I have an interface like this:

   public interface IEventListener
   {
       public <T extends MyCustomObject> void onEvent(final T object);

       public <T extends MyCustomObject> void onEventTest2(final T object);
   }

and in some other class that implements this interface i want call the same method but define whatever parameter i want like:

public class MyClass implements IEventListener
{
   @Override
   public <T> void onEvent(final Player player)
   {
     // My code here
   }

   @Override
   public <T> void onEventTest2(final Item item)
   {
     // My code here
   }
}

How can i achieve this ?

Upvotes: 0

Views: 31

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198033

It seems very clear, now, that your generics should be on the type, not the method -- and with your edit, you'll just need multiple parameters, i.e.

interface IEventListener<T1 extends MyCustomObject, T2 extends MyCustomObject> {
   void onEvent(T1 object);

   void onEventTest2(T2 object);
}

public class MyClass implements IEventListener<Player, Item> {
   @Override public void onEvent(Player player) { ... }
   @Override public void onEventTest2(Item item) { ... }
}

There is not going to be any way you can have the generics on the methods; they must be on the type.

Upvotes: 1

Related Questions