jeudi 20 mai 2021

Java Reflection: How to obtain an instance of Class

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!





Aucun commentaire:

Enregistrer un commentaire