[英]generic type to static method
Example is pretty simple.例子很简单。 What I want is written.
我想要的写出来了。 The problems are in the comments.
问题在评论里。
import java.util.*;
class Main
{
private static class X<T> {
public static T get() { return new T(); }
}
public static void main(String[] args)
{
System.out.println(X<Interger>.get()); // illegal start of type
// commenting out above yields:
// error: non-static type variable T cannot be referenced from a static context
}
}
The real confounder to me is the error: non-static type variable T cannot be referenced from a static context
.对我来说真正的混淆是
error: non-static type variable T cannot be referenced from a static context
。 The error seems clear: the class & method are static but the type variable isn't.错误似乎很清楚:类和方法是静态的,但类型变量不是。 Can I make the type variable work in this static context.
我可以让类型变量在这个静态上下文中工作吗?
Further, as the example is written, I don't understand why I get an illegal start of type
error with nothing else.此外,在编写示例时,我不明白为什么我会得到
illegal start of type
错误的illegal start of type
没有其他任何内容。 Is this because the error about the non-static type variable is hidden?这是因为非静态类型变量的错误被隐藏了吗?
You can't do new T()
.你不能做
new T()
。 For one thing, there is no guarantee that T
has an accessible no-args constructor.一方面,不能保证
T
具有可访问的无参数构造函数。 Relevant here, there is no no-arg constructor for Integer
.与此处相关,
Integer
没有无参数构造函数。
Static methods, as well as instance methods and constructors, can have type parameters.静态方法以及实例方法和构造函数都可以具有类型参数。
public static <T> T get() {
// Can only legally return null or throw.
...
}
...
System.out.println(X.<Integer>get());
What to use instead?用什么代替? Possibly an abstract factory of some sort, possibly
java.util.function.Supplier
.可能是某种抽象工厂,可能是
java.util.function.Supplier
。
While the type X
is generic, the class X
is not.虽然类型
X
是泛型的,但类X
不是。 In Java, there are no "generic classes" (only generic types).在 Java 中,没有“泛型类”(只有泛型类型)。 What was most probably intended is a generic parameter on the static method:
最有可能的意图是静态方法上的泛型参数:
private static class X<T> {
public static <T> T get() {
return ...;
}
}
Also, since generics are erased , one cannot instantiate T
(thus the three dots in the code above).此外,由于泛型被擦除,不能实例化
T
(因此上面代码中的三个点)。
One would call the method like such:人们会像这样调用该方法:
...
X.<SomeConcreteType>get();
I think Supplier maybe more suitable for you than static X<T>.get
:我认为 Supplier 可能比 static
X<T>.get
更适合你:
public static class aClass {}
public static <T> aMethodWantToUseX(Supplier<T> x) {
T t = x.get();
}
aMethodWantToUseX(aClass::new)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.