What I'm trying to do is to get a generic typearg of a Field using
Type type = f.getGenericType();
if (type instanceof ParameterizedType) {
ParameterizedType ptype = (ParameterizedType) type;
// ...
Class<?> typearg0 = ??? // ptype.getActualTypeArguments()[0]
}
(where f
is an instance of java.lang.Field
). I need that instance of Class<?>
to perform a Foo.class.isAssignableFrom(typearg0)
check later, which only takes Class<T>
es as an argument. At the same time, I know (or expect) said typearg0
to be a parameterized type as well, so there's a contradiction: typearg0
cannot be Class<?>
and ParameterizedType
at the same time, because Class<?>
is itself a class and does not implement ParameterizedType
.
Can I achieve the isAssignableFrom()
check in any other way? Or is my goal generally impossible to achieve?
Thank you very much!
Edit:
Here is an example:
Suppose you expect a Field of type Map<Foo, Set<Bar>>
, but all you got is a java.lang.reflect.Field
instance. Now, you don't want it to precisely match Map<Foo, Set<Bar>>
, you just want the respective types to be instances of Map
or Set
. It is not a rigid specification check, it's more of a "sanity check". I would attempt this check like this:
- Get the field type as a class (
.getType()
) - Check whether
Map
is assignable from the field type - Get the field type as a (possibly) parameterized type (
.getGenericType()
) - Check that the first generic parameter is
Foo
(this should be an exact match) - Get the second generic parameter as a class
- Check whether
Set
is assignable from this nested type - Check whether the nested type is itself a
ParameterizedType
and cast it - Check that the first generic parameter of the nested type is
Bar
(this should be an exact match)
However, I don't know how to achieve 5 and/or 6.
(using java 11)