I tried to compile the following code:
public interface Foo<T> {
public interface Bar {
public void bar(T t);
}
void foo(T t);
}
But I get this error: "Foo.this cannot be referenced from a static context."
Specifically, I get it on the "T" in bar(T t). However foo(T t) does not produce the same error. I don't understand why that's a static context and what the error really means.
8. Java Generic Classes and Subtyping. We can subtype a generic class or interface by extending or implementing it. The relationship between the type parameters of one class or interface and the type parameters of another are determined by the extends and implements clauses.
Cannot Create Arrays of Parameterized Types. Cannot Create, Catch, or Throw Objects of Parameterized Types. Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase to the Same Raw Type.
Many people are unsatisfied with the restrictions caused by the way generics are implemented in Java. Specifically, they are unhappy that generic type parameters are not reified: they are not available at runtime. Generics are implemented using erasure, in which generic type parameters are simply removed at runtime.
A "nested" interface (Bar in your example) is implicitly static. So it can't access instance specific information related to Foo, such as its generic type.
See for example JLS #8.5.1:
A member interface is implicitly static
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With