deamon
deamon

Reputation: 92407

How to make the generic return type of a method dependend of the parameter type?

I have a convert method, which takes a String and a class as arguments and constructs an object of the given class, which will be returned.

The usage should look like this

Something s = Converter.convert("...", Something.class)

Is it possible to express this with Java generics?

Upvotes: 3

Views: 209

Answers (2)

GuruKulki
GuruKulki

Reputation: 26418

You can do like this:

public class Main { 

public static void main(String[] args) throws Exception { 

   String s = convert(new String(), String.class);
}

private static <T>T convert(String string, Class<T> class1) {
     // TODO Auto-generated method stub
     return (T) new String();
} 
} 

EDIT: in your method arguments its not class its Class and while returning you should cast it to T ans return, like

     return (T) mapper.readValue(json, target);

Upvotes: 1

Bozho
Bozho

Reputation: 597076

It would be:

Class<T>

i.e.

public static <T> T convert(String source, Class<T> tClass)

Upvotes: 7

Related Questions