Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics with class and nested static interface

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){
        ...
    }
);
like image 844
Gabriel Llamas Avatar asked Mar 06 '11 16:03

Gabriel Llamas


1 Answers

A static nested class or nested interface (which is always static, by the way) has no relation to its outer class (or interface) apart from namespace nesting and access to private variables.

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

(As an example in the standard API, look for the interface Map.Entry<K,V>, nested inside the interface Map<K,V>, yet has no access to its type parameters and needs to declare them again.)

like image 100
Paŭlo Ebermann Avatar answered Oct 04 '22 21:10

Paŭlo Ebermann