Java Generators with Class and Nested Static Interface

I want to use a generic class inside a nested static interface. My goal is to do something like this:

public class MyClass<T>{ private MyInterface task; public static interface MyInterface{ void aMethod (T item); } } 

But I get the error: I can’t make a static reference to the non-static type T. If I make some changes (below), I can use the generic type inside the interface, but I want to avoid this method because it is redundant to write one class 2 times: one for MyClass and one for MyInterface.

 public class MyClass<T>{ private MyInterface<T> task; public static interface MyInterface<T>{ void aMethod (T item); } } 

Thanks.

EDIT : I want to do this:

 MyClass c = new MyClass<String> (); c.setInterface (new MyClass.MyInterface (){ @Override public void aMethod (String s){ ... } ); 

or

 MyClass c = new MyClass<AnotherClass> (); c.setInterface (new MyClass.MyInterface (){ @Override public void aMethod (AnotherClass s){ ... } ); 
+6
java generics class interface
source share
2 answers

A static nested class or nested interface (which is always static, by the way) has nothing to do with its external class (or interface), except for nesting of the namespace and access to private variables.

So, the parameter of the type of the outer class is not available inside the nested interface in your case, you must define it again. To avoid confusion, I recommend using a different name for this internal parameter.

(As an example, in the standard API, find the Map.Entry<K,V> interface, nested inside the Map<K,V> interface, but do not have access to its type parameters and must declare them again.)

+17
source share

This is not redundant. With static interface:

 MyClass.MyInterface<String> myInstance; 

and with the non-stationary class innter (the interface is always static):

 MyClass<String>.MyInterface myInstance; 

More real example:

 Map<String, Integer> map = ...; for (Map.Entry<String, Integer> entry : map.entrySet()) { ... } 

The static approach has the advantage that you can import a nested type and still specify type parameters:

 class ClassWithAReallyLongName<T> { static interface Entry<T> { } } 

and

 import my.package.ClassWithAReallyLongName.Entry; class Foo { Entry<String> bar; } 

although you should use this idiom with caution so as not to confuse the reader.

+6
source share

All Articles