没有参数的通用方法
我对我的代码感到困惑,其中包含一个不带参数的generics方法,因此这种方法的返回generics类型是什么,例如:
static example getObj() { return new example() { public T getObject() { return null; } }; }
这被称为:
example exm = getObj(); // it accepts anything String like in this case or Object and everything
界面example's
定义是:
public interface example { T getObject(); }
我的问题: example exm
接受String,Object和所有内容。 那么在什么时候generics返回类型被指定为String以及如何?
编译器根据赋值的LHS上使用的具体类型推断出T
的类型。
从这个链接 :
如果类型参数未出现在方法参数的类型中,则编译器无法通过检查实际方法参数的类型来推断类型参数。 如果类型参数出现在方法的返回类型中,则编译器会查看使用返回值的上下文。 如果方法调用显示为赋值的右侧操作数,则编译器会尝试从赋值的左侧操作数的静态类型推断方法的类型参数。
链接中的示例代码与您问题中的代码类似:
public final class Utilities { ... public static HashSet create(int size) { return new HashSet (size); } } public final class Test public static void main(String[] args) { HashSet hi = Utilities.create(10); // T is inferred from LHS to be `Integer` } }
您可以执行以下通用静态声明:
example x = getObj(); String s = x.getObject();//no casting required, good!
但是getObject
方法变得模糊,因为你将如何派生return
类型:
public T getObject() { //how would this method return based on T? //one way to always cast to T say: //return (T) obj; // but do you figure out obj based on T, NOT possible! due to type eraser at runtime // a custom logic can produce diff type obj, but that's force casting and no generic usage return null; }
最好通过Class
参数提供T
信息作为参数:
public T getObject(Class clazz) { //clazz can be used to derive return value .. }