navotera navotera - 7 months ago 21
Android Question

Class as parameter on static method - Java

I want to create static method and using jackson on that method to convert json to some object. what i dont understand how to use class as parameter on my static method.

here my code :

static Object stringToObject(String jsonString, Class someClass) {
ObjectMapper mapper = new ObjectMapper();

SomeClass Object = mapper.readValue(jsonString, someClass.class);
//handling some exception

return Object;

that code would error... can someone give me advice how to accomplish that thanks


Since you always want to keep type-safety then the best solution is to use a generic method which is a method with a type variable.

In your situation ObjectMapper::readValue is already a generic method so what you need is to use the correct syntax for your declaration:

static <T> T stringToObject(String jsonString, Class<T> clazz) {
  ObjectMapper mapper = new ObjectMapper();
  return mapper.readValue(jsonString, clazz);

static void test() {
   Foo foo = stringToObject("...", Foo.class);

In this way Java type inference can make its work and you don't have to specify anything.