开发者

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

开发者 https://www.devze.com 2022-12-28 06:25 出处:网络
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.

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

精彩评论

暂无评论...
验证码 换一张
取 消