Resolving a Generic Type with the Spring Framework

In the case of generic beans sometimes you need to get the generic type value for some specific reasons. A typical example could be parsing some data into the type.

Following code shows you how to parse a JSON data into the specific structure defined by a generic class.

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.GenericTypeResolver;
// ...

public class MyDataBean<T extends MySuperData> {

    private final Class<T> genericType;

    private final ObjectMapper objectMapper = new ObjectMapper();

    public MyDataBean() {
        this.genericType = (Class<T>) GenericTypeResolver.resolveTypeArgument(getClass(), MyDataBean.class);

    public T parseData(String jsonData) {
    	return objectMapper.readValue(jsonData, this.genericType);

Spring tool GenericTypeResolver will set the genericType class value which is later used as the parameter for the JSON parsing.

It's easy!