为什么泛型类型不能在静态方法中声明为返回类型?

Why are generic types unable to be declared as a return type in static methods?

提问人:Will Franzen 提问时间:9/10/2021 更新时间:9/10/2021 访问量:86

问:

我理解为什么由于其静态性质而无法将参数传递给第二种方法,但是为什么当我尝试将其声明为返回类型时会发生错误?删除类型参数可以解决此问题,但随后我留下了警告:参数化类“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;
    }
}
Java 泛型 静态方法 原始类型

评论

3赞 luk2302 9/10/2021
因为应该是什么,所以你没有修复类型的类的实例。您可以仅为静态方法引入第二个泛型类型参数:。Mpublic static final <P> InterestPoint<P> validate(InterestPoint<P> interestPoint) {
4赞 Matteo NNZ 9/10/2021
您可以将其写成 ,但请注意,此静态方法的 M 与您在包装类的模板中传递的 M 完全无关,因为该方法是静态的,因此与类本身的实例无关。public static <M> InterestPoint<M> validate(InterestPoint<M> interestPoint)

答:

2赞 Mureinik 9/10/2021 #1

泛型类型参数属于实例,而静态方法不属于特定实例,而是属于类。让静态方法返回泛型类型的方法是直接向其添加类型参数。例如:M

public static final <N> InterestPoint<N> validate(InterestPoint<N> interestPoint) {
    interestPoint.validate();
    return interestPoint;
}