【发布时间】:2016-04-04 15:35:34
【问题描述】:
我想要达到的目标如下:
public class Foo {
Object o;
public Foo(Object o) { //takes object
this.o = o;
}
public <T> T getO() { //the return type of this should be the object type
return (T) o;
}
}
例如:
Object o = "123"; // imagine this comes from external system and can be anything
Foo foo = new Foo(o);
String foo = foo.getO(); //returns String
我看到一些使用 Google Guava TypeToken 执行类似操作的示例,但无法获得我想要的行为。
【问题讨论】:
-
如果
Foo不是泛型类型,这是行不通的 - 编译器如何知道如何处理对Foo.getO()的调用? -
您需要使 Foo 通用或使用反射...这里有类似的东西吗? stackoverflow.com/questions/75175/…
标签: java generics reflection