java Java泛型:不能从静态上下文中引用非静态类型变量T

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10963601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 03:14:40  来源:igfitidea点击:

Java Generics: non-static type variable T cannot be referenced from a static context

javagenerics

提问by auser

interface A<T> {

    interface B {
       // Results in non-static type variable T cannot
       // be referenced from a static context
       T foo(); 
    }

}

Is there anyway round this? Why is T seen as static when referenced from A.B?

反正有这个吗?为什么从 AB 引用时 T 被视为静态?

采纳答案by Jigar Joshi

All member fields of an interface are by default public, staticand final.

接口的所有成员字段默认为public,staticfinal

Since inner interface is staticby default, you can't refer to Tfrom static fields or methods.

由于static默认情况下内部接口是,您不能T从静态字段或方法中引用。

Because Tis actually associated with an instance of a class, if it were associated with a static field or method which is associated with class then it wouldn't make any sense

因为T实际上与类的实例相关联,如果它与与类相关联的静态字段或方法相关联,那么它就没有任何意义

回答by Akhi

How about something like this.

这样的事情怎么样。

public interface A<T> {

     interface B<T> extends A<T>{

       T foo(); 
    }

}

回答by Dodd10x

Your inner interface doesn't know what T is. Try this.

你的内部接口不知道 T 是什么。试试这个。

interface A<T> {

    interface B<T> {
       T foo(); 
    }

}