0
class X {
    private String y;
}

class T {
    private List<X> w;
    private void run() {
        Field f = getClass().getDeclaredField("w");
        Class t = f.getType();// t is "Class of interface java.util.List", but what I want is "Class of java.util.List<X>", how to achieve it
    }
}

I have tried getAnnotatedType or something, but nothing valuable found

http8086
  • 1,306
  • 16
  • 37

1 Answers1

1

You could try ((ParameterizedType)f.getGenericType()).getActualTypeArguments() to get a Type[] array which in your case should have 1 element: X.class. Note that this only works in cases where you can use reflection (i.e. not for local variables) and if the types are boundaries you'd need to handle it differently. Also ,you'd need to check if getGenericType() really returns a ParameterizedType.

Other methods you might want to look into:

  • for classes use getTypeParameters(), this would return an empty array for non generic classes
  • for method return types use getGenericReturnType()
  • for method and constructor parameters use getGenericParameterTypes(), this would return an empty array for no-arg methods

Some types/interfaces they might return:

  • actual classes for raw types
  • ParameterizedType for generic fields, parameters and return types
  • TypeVariable for generic type parameters without wildcards
  • WildcardType for generic type parameters with a wildcard
Thomas
  • 87,414
  • 12
  • 119
  • 157
  • thank you bro. but I need the exact type in json deserialization process, I have to tell `com.fasterxml.jackson.databind.ObjectMapper#readValue(java.lang.String, java.lang.Class)` to build an object of `java.util.List` – http8086 Sep 16 '21 at 08:06
  • 1
    @http8086 in that case you might need to have a look into the `TypeReference` class provided by Jackson. You should also state your actual goals and requirements in your questions directly since your's now would be a [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Thomas Sep 16 '21 at 08:24