Alex Rivera | Logout

Java generics with class and nested static interface

Asked 2011-03-06T16:54:18.340
11

I want to use a generic class inside a nested static interface. My objective 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: Cannot make a static reference to the non-static type T. If I do some changes (below) I can use a generic type inside an interface, but I want to avoid this method because it's redundant to write the same 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){
        ...
    }
);
Edit
Report

1 Answer

8

It's not redundant. With a static interface:

MyClass.MyInterface<String> myInstance;

and with a non-static innter class (an interface is always static):

MyClass<String>.MyInterface myInstance;

A more real world example:

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

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

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

and

import my.package.ClassWithAReallyLongName.Entry;

class Foo {
    Entry<String> bar;
}

though one should use that idiom with caution as to not confuse the reader.

answered 2011-03-06T16:59:43.383

Your Answer