2011-10-10 67 views

回答

1

你可以使用泛型来推断返回类型,就像这样:

public <T> T methodX() { 
    return (T) someValue; //Note that you should ensure that this cast succeeds or catch the possible ClassCastException here 
} 

//call it like this: 
String s = methodX(); 

请注意,你需要确保你可以转换为推断出的类型,所以你可能想通过Class<T>作为参数,以检查T的类型。

仅仅从赋值中推断T的类型可能会有帮助,如果实际返回的泛型对象的泛型参数为T。看看例如Collections.emptyList(),它返回一个空的List<T>(因此列表中没有任何元素不是T类型)。

您还可以设置为T类型界限:

public <T extends Number> T methodX() { 
    return (T) someValue; 
} 

//would compile 
Integer i = methodX(); 

//this would not compile, since s is not a number 
String s = methodX(); 
0

如果您尝试执行类似String str = new Object()的操作,则会出现类型不匹配。

如果你知道这个方法返回,说String,也就是说,如果它看起来像

public Object yourMethod() { 
    return "Hello World"; 
} 

,那么你可以投在呼叫侧的结果,就像这样:

String result = (String) yourMethod(); 

(如果不实际上返回String,你会得到一个ClassCastException!)


如果你已经声明为

public String yourMethod() { 
    ... 
} 

的方法,那么你无法返回Object,你必须返回一个String

+0

我使用泛型,所以我不知道我返回的是什么类型。有没有办法将Object类型返回到原始类型? – Graham

相关问题