Resolving a Generic Type with 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;
// ...

@Component
public class MyBean<T extends MySuperBean> {

  private final Class<T> genericType;

  private final ObjectMapper mapper = new ObjectMapper();

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

  public T parseData(String json) {
    return mapper.readValue(json, this.genericType);
  }
}

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

Happy resolving!