简体   繁体   中英

Java getter return type based on object type

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM