tags:

views:

84

answers:

2

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?

+7  A: 

It would be:

Class<T>

i.e.

public static <T> T convert(String source, Class<T> tClass)
Bozho
+1 for lowercasing the argument as well.
BalusC
Didn't work for me. I've modified my question ..
deamon
@deamon: It's `Class` with uppercase, not `class`. Check Bozho's answer once again.
BalusC
One small cap for me, one giant cap for the computer ;-)
deamon
+1  A: 

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);
GK
In English, it's "you", not "u". Further, code blocks are to be indented with 4 spaces. You can select code and then press the `010101` button or `Ctrl+K` to get it indented. Also see message formatting rules in the right hand column.
BalusC
@GK I formatted it with correct indentation, there was no need to replace my edit :)
Bozho
@BalusC Thanks for your advise. I didnt know how to format. @Bozho thanks.
GK