vendredi 17 juin 2016

How to use reflection to access details of abstract fields

I have a class which is of the following form:

public class SomeClass {
  public static AbstractClass<Boolean> variable1 = AbstractClass.create("key", value);
}

The create function takes care of actually generating a concrete instance of AbstractClass. The constructor of AbstractClass is protected. I want to write a test, which access all such variables[1...] and perform a test on their "key". How can I do this ?

Here's my try on this:

for (Field field : allFields) {
  Class<?> targetType = field.getType();
  AbstractClass<?> flag = (AbstractClass<?>) field.get(targetType.newInstance());
  assertTrue(flag.getKey().startsWith("xyz"));

Clearly, using newInstance can't work as targetType here is abstract, and throws InstantiationException.

I think this is impossible, but just wondering if there's any way to get around this ?





Aucun commentaire:

Enregistrer un commentaire