lundi 4 avril 2016

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:

Foo foo = new Foo("123"); //passing String
String foo = foo.getO(); //return String

Foo foo = new Foo(123f); //passing float
float foo = foo.getO(); //return float

I saw a few examples doing something simmilar using Google Guava TypeToken but couldn't get exactly the behaviour I want.





Aucun commentaire:

Enregistrer un commentaire