无法静态引用非静态类型T

无法静态引用非静态类型T

本文介绍了(泛型)无法静态引用非静态类型T的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行Demo类将在SomeClass中调用静态方法newInstance来调用构造函数并打印问候

running the Demo class will invoke a static method newInstance in SomeClass to call the constructor and printing hello

定义方法将包括带有参数的返回类型+方法名称

defining a method will include a return type + method name with arguments

newInstance的返回类型是< T> SomeClass< T>在我看来很奇怪因为我的班级叫做SomeClass< T>而不是< T> SomeClass< T>

the return type for newInstance is <T>SomeClass<T> seems weird to mesince my class is called SomeClass<T> instead of <T>SomeClass<T>

要指出的另一件事是,我可以在< T>和SomeClass< 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.

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);
    }
}

推荐答案

什么是静态方法?该方法适用于该类,而不适用于特定实例.类签名public class SomeClass<T>中的通用参数T仅可用于特定实例(因此为non-static type T).例如SomeClass<String>其中[T = String].

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].

通过在public static <T>SomeClass<T> newInstance(Class<T> clazz)的方法签名中包含<T>.你是在说对于此方法,有一个通用类型参数T.该T与类签名中的T是分开的.因此也可能是C,即public static <C> SomeClass<C> newInstance(Class<C> clazz).或完全不同的东西.

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>包含在该方法中,则编译器会认为您正在尝试在类签名中使用T.这是非法的.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:45