[英]Why type parameter required before return type for static generic methods
The following noGood
method gives a compilation error because it omits the formal type parameter immediately before the return type T
. 以下
noGood
方法给出了编译错误,因为它在返回类型T
之前省略了正式类型参数。
public static T noGood(T t) {
return t;
}
Could somebody please help me understand that why is it required for a static generic method to have a type parameter before the return type? 有人可以帮我理解为什么静态泛型方法在返回类型之前需要一个类型参数? Is it not required for a non-static method?
非静态方法不需要它吗?
The type parameter ( T
) is declared when you instantiate the class. 在实例化类时声明类型参数(
T
)。 Thus, instance methods don't need a type argument, since it's defined by the instance. 因此,实例方法不需要类型参数,因为它是由实例定义的。
static
methods, on the other hand, don't belong to an instance - they belong to the class. 另一方面,
static
方法不属于实例 - 它们属于类。 Since there's no instance to get the type information from, it must be specified for the method itself. 由于没有实例来获取类型信息,因此必须为方法本身指定。
T
wasn't defined. T
没有定义。 The order of modifiers and the return type remains the same. 修饰符的顺序和返回类型保持不变。
public static <T> T noGood(T t) {
return t;
}
When you're using generic, you need to declare them, using <>
notation 当您使用泛型时,需要使用
<>
表示法声明它们
In a class 在课堂上
public class Foo<T, U, V>{ }
In a method, before the return type 在一个方法中,返回类型之前
public static <T, U extends Number, V> T foo(T t) { U u = ..; ... } public static <T> int foo(T t) { ... }
First of all, this is pretty standard in languages. 首先,这是非常标准的语言。 Even in C++:
即使在C ++中:
template <class myType>
myType GetMax (myType a, myType b) {
return (a>b?a:b);
}
You declare the type parameter above a generic function. 您将类型参数声明为泛型函数。
When its a member function of a class, it has access to the class's type parameters. 当它是类的成员函数时,它可以访问类的类型参数。 When its static it doesn't, so you need to declare them explicitly.
如果它不是静态的,那么你需要明确地声明它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.