java (泛型)不能对非静态类型 T 进行静态引用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36386295/
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
(Generics)Cannot make a static reference to the non-static type T
提问by securenova
running the Demo class will invoke a static method newInstance in SomeClass to call the constructor and printing hello
运行Demo类会调用SomeClass中的静态方法newInstance来调用构造函数并打印hello
defining a method will include a return type + method name with arguments
定义一个方法将包括一个返回类型+带有参数的方法名称
the return type for newInstance is <T>SomeClass<T> seems weird to me since my class is called SomeClass<T> instead of <T>SomeClass<T>
newInstance 的返回类型是 <T>SomeClass<T> 对我来说似乎很奇怪,因为我的类被称为 SomeClass<T> 而不是 <T>SomeClass<T>
why do i need the <T> in front of the SomeClass<T> ? it seems that if I don't include it there will be an common error called Cannot make a static reference to the non-static type T
为什么我需要在 SomeClass<T> 前面的 <T> ?似乎如果我不包含它,就会出现一个名为无法对非静态类型 T 进行静态引用的常见错误
another thing to point out is that I can put many spaces between <T> and SomeClass<T> so it doesn't seem like they need to be together.
另一件事要指出的是,我可以在 <T> 和 SomeClass<T> 之间放置许多空格,因此它们似乎不需要在一起。
public class SomeClass<T> {
public static <T>SomeClass<T> newInstance(Class<T> clazz){
return new SomeClass<T>(clazz);
}
private SomeClass(Class<T> clazz){
System.out.println("hello");
}
}
public class Demo {
public static void main(String args[])
{
SomeClass<String> instance = SomeClass.newInstance(String.class);
}
}
回答by Jorn Vernee
What is a static method? A Method that works on the class, and not a specific instance. The generic parameter T
in the class signature public class SomeClass<T>
is only available for a specific instance (hence non-static type T
). e.g. SomeClass<String>
where the [T = String]
.
什么是静态方法?一个在类上工作的方法,而不是一个特定的实例。T
类签名中的泛型参数public class SomeClass<T>
仅适用于特定实例(因此non-static type T
)。例如SomeClass<String>
在哪里[T = String]
。
By including <T>
in the method signature of public static <T>SomeClass<T> newInstance(Class<T> clazz)
. You're saying that; for this method, there is a generic type argument T
. This T
is separate from the T
in the class signature. So it might as well be C
i.e. public static <C> SomeClass<C> newInstance(Class<C> clazz)
. Or something completely different.
通过包含<T>
在 的方法签名中public static <T>SomeClass<T> newInstance(Class<T> clazz)
。你是这么说的;对于此方法,有一个泛型类型参数T
。这T
是从不同的T
类中的签名。所以它也可能是C
ie public static <C> SomeClass<C> newInstance(Class<C> clazz)
。或者完全不同的东西。
But if you don't include <T>
with the method, the compiler thinks you're trying to use the T
in the class signature. Which is illegal.
但是如果您不包含<T>
在方法中,编译器会认为您正在尝试T
在类签名中使用 。这是非法的。