Java – classes that implement interfaces without type parameters cannot be compiled
I have the following test codes:
public interface Container<I> { public void addClass(Class<?> clazz); } public class MyContainer implements Container { public void addClass(Class<?> clazz) {} }
When trying to compile these two classes, I received the following error:
If I add a type to the container interface in mycontainer (for example < Object >), I will not receive an error
The problem is that I introduce type parameters into the container, which is part of the public API, so for compatibility, I can't make all implementation classes unable to compile
Does anyone have an idea? Is this a type erase problem? Is there a solution?
Solution
I think the problem is that if you use primitive types anywhere in the class declaration, you will choose to exit generics So this will work – note the parameter changes
public class MyContainer implements Container { public void addClass(Class clazz) {} }
Starting from section 4.8 of the JLS:
I believe this is relevant... Container < T > The deletion of addclass (class clazz) is addclass (class clazz)
But basically, unless this is real legacy code, you should introduce type parameters into the interface as major changes