运行Demo类会调用SomeClass中的静态方法newInstance来调用构造函数并打印hello
定义一个方法将包括一个返回类型+带参数的方法名
newInstance 的返回类型是
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
要指出的另一件事是,我可以在
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);
}
}
最佳答案
什么是静态方法?适用于类而不是特定实例的方法。通用参数 T
在类(class)签名public class SomeClass<T>
仅适用于特定实例(因此 non-static type T
)。例如SomeClass<String>
[T = String]
在哪里.
通过包含 <T>
在 public static <T>SomeClass<T> newInstance(Class<T> clazz)
的方法签名中.你是这么说的;对于此方法,有一个泛型类型参数 T
.这T
与 T
分开在类签名中。所以它也可能是C
即 public static <C> SomeClass<C> newInstance(Class<C> clazz)
.或者完全不同的东西。
但是如果你不包括 <T>
使用该方法,编译器认为您正在尝试使用 T
在类签名中。这是非法的。
关于java - (泛型)不能对非静态类型 T 进行静态引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36386295/