Search code examples
javagenericsjacksonnested-generics

Java get class constant for closed generic type (instance of Class<T1<T2>>)


I come from a C# background and am having trouble with Java generics. I am trying to call a generic method that requires an instance of Class<T> as a param. Normally this is a matter of passing SimpleType.class. In this case though, the type I need is not a simple type, but has its own type parameter that needs to be included in the Class instance (i.e. I need a Class<OuterType<InnerType>>). How do I get this?

Note: To make things a bit more complicated, this is taking place within another generic method. So while the "outer" type is known at compile type, the inner is known only through its own Class instance. See the code:

public <T> T deserialize(InputStream stream, Class<T> clazz) {
    com.fasterxml.jackson.databind.ObjectMapper mapper = getJsonMapper();
    //Need an instance of Class<MessageWrapper<T>>
    MessageWrapper<T> wrapper = mapper.readValue(stream, MessageWrapper.class);
    return wrapper.message;
}

private class MessageWrapper<T> {
    public T message;
}

Solution

  • What you can try is this:

    public <T> T deserialize(InputStream stream, Class<T> clazz) {
        com.fasterxml.jackson.databind.ObjectMapper mapper = getJsonMapper();
        //Need an instance of Class<MessageWrapper<T>>
        MessageWrapper<T> wrapper =mapper.readValue(jsonString, new TypeReference<MessageWrapper<T>>() {});
        return wrapper.message;
    }
    

    As well, the class should be or static, or public within its own file:

    public class MessageWrapper<T> {
        public T message;
    }
    

    Or:

    private static class MessageWrapper<T> {
        public T message;
    }