We can get away with this in .NET:

interface I<A> {}
interface I<A, B> {}

... but in Java, the same code will result in a compilation error.

That's interesting, given that even if the type information is gone at runtime, one would expect the information about the number of type parameter to still be there.

If this limitation is related to type erasure, can someone explain why?

有帮助吗?

解决方案

It's not related to type erasure so much as to the ambiguity that would arise from using the raw type:

I eye = null;  // which 'I' is it?

Raw types are allowed in order to accommodate code written before generics were introduced in JDK 5.0.

其他提示

In java, a generic class/interface has a fixed number of generic parameters. It's just the way the language is defined.

The closest thing to what you are talking about might be:

interface I<A> {}
interface J<A, B> extends I<A> {}

an instance of J is still assignable to a variable of type I.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top