Given a class
class EnvironmentHolder<V> {
protected Map<String,V> environment;
// Get the Type of V using Google's Guava library; this part
// works okay
protected final Type VALUE_TYPE = new TypeToken<V>() {}.getType();
...
public void importEnvironment(Class aClass) {
}
}
where V
is some reference type, I'm trying to collect all of the static members of aClass
which are "assignable to" a class of type V
— that is, those which are subclasses, implementations of, or the same class as V
.
How do I do this? I'd like to use the following:
for (Field field : aClass.getFields()) {
((Class) V).isAssignableFrom(field.getType())
}
I see that Class
is indeed an implementer of Type
, but I'm not sure how to perform a cast safely. (Type
also encompasses non-reference types, which are not Class
es.)
NB: Please don't say, "Type erasure preludes doing this at runtime" until you have thought it through. A fair number of questions have that as a virtually automatic response, which would seem to imply that a reflection API is impossible to implement in Java.
Thanks!
Aucun commentaire:
Enregistrer un commentaire