I've an interface Message
with two implementations MessageA
and MessageB
.
Now I have the following generic class that takes a type variable T
that extends Message
. I want a method test
to act in one way if the argument is T
(or a subtype) and in an other way if the argument is an other implementation of Message
:
I tried this, but it does not work because of erasure :
public class MyClass<T extends Message>
{
public Integer test(T m)
{
System.out.println( "This is the good one." );
return m.f(7);
}
public <S extends Message> Integer test(S m)
{
System.out.println("I'm not the good one");
return m.f(7);
}
}
I could do explicit type checking, but I guess that there exists a cleaner way to reach my goal.
EDIT
I prefer to use overriding or overloading because in my project, I will have a class MyClassA implements MyClass<MessageA>
that will implement the method test(MessageA m)
. But I want to implement the "wrong" case in the base generic class.
The following makes the work :
public class MyClassA extends MyClass<MessageA>
{
public Integer test(Message m)
{
if (m instanceof MessageA)
{
return m.f(7);
}
else
{
System.out.println("Bad type.");
return 0;
}
}
}
But it forces me to implement a if-then
block with print("bad type")
in every instantiation of my generic MyClass<T extends Message>
(for the sake of code duplication).
EDIT Based on the accepted solution, I posted a fully-functional minimal example here.