Reputation: 9549
What I am trying to achieve is something like the following:
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;
}
}
For example:
Object o = "123"; // imagine this comes from external system and can be anything
Foo foo = new Foo(o);
String foo = foo.getO(); //returns String
I saw a few examples doing something similar using Google Guava TypeToken
but couldn't get exactly the behavior I want.
Upvotes: 0
Views: 1604
Reputation: 4403
You can do what you want if you make Foo have the correct type
public class Foo<T> {
T data;
public Foo(T d)
{
this.data = d;
}
public T getData()
{
return data;
}
}
Then your examples will work as:
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
EDIT: the original question was updated slightly. However, the basic problem remains that a Java method must declare its return type. One can get close if one can use covariant
returns in some fashion by extending a hierarchy. There are examples Overriding a method with different return types and Can overridden methods differ in return type.
One could also consider a Factory pattern to assist with the approach. So it would be
Foo foo = FooFactory.geetFoo(originalData); // the specific foo would vary
String s = foo.getData();
Upvotes: 4