我想要达到的目标如下:
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
做类似事情的示例,但无法完全达到我想要的行为。
答案 0 :(得分:4)
如果你让Foo拥有正确的类型
,你可以做你想做的事public class Foo<T> {
T data;
public Foo(T d)
{
this.data = d;
}
public T getData()
{
return data;
}
}
然后您的示例将起作用:
Foo<String> foo = new Foo<>("123"); //passing String
String foo = foo.getData(); //return String
Foo<Float> foo = new Foo<>(123f); //passing float
float foo = foo.getData(); //return float
编辑:原始问题稍有更新。但是,基本问题仍然是Java方法必须声明其返回类型。如果可以通过扩展层次结构以某种方式使用covariant
返回,则可以接近。有Overriding a method with different return types和Can overridden methods differ in return type示例。
还可以考虑使用工厂模式来协助该方法。所以它会是
Foo foo = FooFactory.geetFoo(originalData); // the specific foo would vary
String s = foo.getData();