javascalareflect

How to pass class object as a variable in Java


I have a function below which accepts a string and converts it into a JSON Object using Jackson Api in java.

public JobConfig fromJson(String config)  {
        JobConfig lib = null;
        try {
            lib = mapper.readValue(config, JobConfig.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return lib;
    }

JobConfig.class is my JAVA Pojo for the JSON Struncture.

I call this function like below -

JobConfig jobConfig = utils.fromJson(config);

The issue is i have to write another function for another JSON so i want this to be dynamic enough so when i call this function, i can also send the JobConfig.class class and it should return accordingly.

In scala i would do something like this -

def fromJson[T : Manifest](s: String): T = Serialization.read[T](s)

Not sure how to do this in Java. Open to new learning.


Solution

  • in java you can use generics as well.

    your code would be like:

    public class Main<T> {
        public T fromJson(String config)  {
            T lib = null;
            try {
                lib = mapper.readValue(config, Class<T>);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return lib;
        }
    }