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

查看:15
本文介绍了带有类和嵌套静态接口的 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);
    }
}

谢谢.

编辑:我想这样做:

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.

因此,在您的情况下,外部类的类型参数在嵌套接口内不可用,您应该重新定义它.为避免混淆,我建议为这个内部参数使用不同的名称.

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,嵌套在接口Map中,但无法访问其类型参数,需要再次声明.)

(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天全站免登陆