Java泛型与类和嵌套静态接口 [英] Java generics with class and nested static interface

查看:122
本文介绍了Java泛型与类和嵌套静态接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在嵌套的静态接口中使用通用类。我的目标是做这样的事情:

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);
    }
}

但我得到错误:到非静态类型T.如果我做一些改变(下面)我可以使用一个通用类型的接口,但我想避免这种方法,因为它是冗余的写同一类2次:一个为MyClass和一个MyInterface。

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);
    }
}

感谢。 b $ b EDIT :我想这样做:

Thanks.

EDIT: I want to do this:

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

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


推荐答案

静态嵌套类或嵌套接口静态)除了命名空间嵌套和访问私有变量之外,与其外部类(或接口)无关。

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.

因此,外部类类在你的case的嵌套接口中不可用,你应该再次定义它。 为避免混淆,我建议为此内部参数使用不同的名称。

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.

(作为标准API中的示例, Map.Entry< K,V> 嵌套在接口 Map< K,V> 到它的类型参数,并需要再次声明它们。)

(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.)

这篇关于Java泛型与类和嵌套静态接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆