How to make the general type of the returned method dependent on the type of the parameter?

I have a method convertthat takes a String and a class as arguments and builds an object of the given class to be returned.

Usage should look like this

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

Can this be expressed using Java generics?

+3
source share
2 answers

This will:

Class<T>

i.e.

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

You can do the following:

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, the arguments of its not a class of its class and, returning, you must give it a T-return, for example

     return (T) mapper.readValue(json, target);
+1
source

Source: https://habr.com/ru/post/1743199/


All Articles