Search code examples
javabackwards-compatibility

How does modifying generics in interface affect backwards compatibility


I have an interface like this,

public interface EventListener<T extends Event>

the problem here is that EventListener is an extremely generic name (which can also be said about Event) and the class Event is not written in a generic way.

Since we are not allowed to do non-backward compatible changes the plan was to modify the generic part of the interface to be more general. So basically I have two options. Either,

a) Add a super interface (eg. GeneralEventListener, let's not mind the name right now) which can take a generic without discrimination

public interface GeneralEventListener<T>

b) Allow EventListener to take an object of type T.

public interface EventListener<T>

I am sure the first one is an allowed modification. However this seems like an unnecessary complication and it would contaminate the namespace. There are neither any need to keep the limitation to Event except from formerly informational. So what I wonder, "is the change (b) binary backwards compatible"?


Solution

  • My previous answer was not completely correct.

    This will cause an issue. Due to the fact that you are using a bounded type, the compiler will replace the type parameter with the bounded type.

    Have a look at: https://docs.oracle.com/javase/tutorial/java/generics/erasure.html

    Of course because generics are used at compile time, your best bet would simply be to make the change and see if the code compiles.