0

I have a method that accepts a com.fasterxml.jackson.core.type.TypeReference and returns an object of the referenced type, but in a certain case I want to just return a new instance of that type.

Example:

public <T> T getProperty(String property, TypeReference<T> typeReference) {
    try {
        return someInstanceOfReferencedType();
    }
    catch (IOException e) {
        return ???;
    }
}

How can I instantiate <T> using typeReference? I can get the Type from it, but not sure what to do from there...

Shaun Scovil
  • 3,905
  • 5
  • 39
  • 58

1 Answers1

-1

You can create an instance of TypeReference as:

List<String> l1 = new TypeReference<ArrayList<String>>() {}.newInstance();

So you can call getProperty method as:

List<String> list = getProperty("property1",new TypeReference <>(){});
//Specify List<> in <> of TypeReference.
CodeF0x
  • 2,624
  • 6
  • 17
  • 28
anand kadu
  • 68
  • 4