提问人:Will Franzen 提问时间:9/10/2021 更新时间:9/10/2021 访问量:86
为什么泛型类型不能在静态方法中声明为返回类型?
Why are generic types unable to be declared as a return type in static methods?
问:
我理解为什么由于其静态性质而无法将参数传递给第二种方法,但是为什么当我尝试将其声明为返回类型时会发生错误?删除类型参数可以解决此问题,但随后我留下了警告:参数化类“InterestPoint”的原始使用。InterestPoint<M>
public record InterestPoint<M>(Coordinate coordinate, M marker) {
public final InterestPoint<M> validate() {
return this;
}
public static final InterestPoint<M> validate(InterestPoint interestPoint) {
interestPoint.validate();
return interestPoint;
}
}
答:
2赞
Mureinik
9/10/2021
#1
泛型类型参数属于实例,而静态方法不属于特定实例,而是属于类。让静态方法返回泛型类型的方法是直接向其添加类型参数。例如:M
public static final <N> InterestPoint<N> validate(InterestPoint<N> interestPoint) {
interestPoint.validate();
return interestPoint;
}
评论
M
public static final <P> InterestPoint<P> validate(InterestPoint<P> interestPoint) {
public static <M> InterestPoint<M> validate(InterestPoint<M> interestPoint)