我对我的代码感到困惑,其中包含一个不带参数的泛型方法,因此这种方法的返回泛型类型是什么,例如:
static <T> example<T> getObj() {
return new example<T>() {
public T getObject() {
return null;
}
};
}
Run Code Online (Sandbox Code Playgroud)
这被称为:
example<String> exm = getObj(); // it accepts anything String like in this case or Object and everything
Run Code Online (Sandbox Code Playgroud)
界面example's定义是:
public interface example<T> {
T getObject();
}
Run Code Online (Sandbox Code Playgroud)
我的问题example<String> exm是:接受字符串,对象和一切.那么在什么时候泛型返回类型被指定为String以及如何?
编译器根据赋值T的LHS使用的具体类型推断出类型.
从这个链接:
如果类型参数未出现在方法参数的类型中,则编译器无法通过检查实际方法参数的类型来推断类型参数.如果类型参数出现在方法的返回类型中,则编译器会查看使用返回值的上下文.如果方法调用显示为赋值的右侧操作数,则编译器会尝试从赋值的左侧操作数的静态类型推断方法的类型参数.
链接中的示例代码与您问题中的代码类似:
public final class Utilities {
...
public static <T> HashSet<T> create(int size) {
return new HashSet<T>(size);
}
}
public final class Test
public static void main(String[] args) {
HashSet<Integer> hi = Utilities.create(10); // T is inferred from LHS to be `Integer`
}
}
Run Code Online (Sandbox Code Playgroud)