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?
It would be:
Class<T>
i.e.
public static <T> T convert(String source, Class<T> tClass)
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);
精彩评论