简体   繁体   中英

Passing a class as a parameter in Java

So I'm using the com.fasterxml.jackson readValue method, which works perfectly fine. It takes in a json String and a POJO that is populated and saved to obj:

Object obj = mapper.readValue(myJsonString, MyPojo.class);

For some reason, if I create a util class that does the same thing, I get an IO exception when I use the readValue() method. When I print c, i get: "class models.UserProfile" . When I print out c.getClass(), I get "class java.lang.class". Is there something wrong with the way I'm passing the class?

    public static Object deserialize(String s, Class c) throws JsonParseException, JsonMappingException, IOException {

    Object obj = mapper.readValue(s, c);
    return obj;
}

You can use generic typing:

MyPojo obj = mapper.readValue(myJsonString, MyPojo.class);

public static <T> T deserialize(String s, Class<T> c)
        throws JsonParseException, JsonMappingException, IOException {
    return mapper.readValue(s, c);
}

MyPojo obj = Util.deserialize(myJsonString, MyPojo.class);

Your utility method however is using a static mapper which might not be such a good idea.

The weirdness found results from not using c.getName() . c.getClass() is of course Class .

The error is passing c.getClass() somehow. Or as likely: the mapper reused.

您正在寻找的可能是c.getName()而不是c.getClass()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM