mercredi 2 octobre 2019

How to call a method for all objects in a class using reflection for below case?

for (final Field field : someClass.getClass().getDeclaredFields()) {
                final Method getId = field.getType().getMethod("getId");
                getId.setAccessible(true);
                SomeComponent obj = (SomeComponent)getId.invoke(field.getType().newInstance());
}

I have objects in someClass who all are subclass of another class which has function getId. I have two objects of the same class in someClass which has following constructor.

 public Object1(SomeComponent id) {
      super(id);
   }

Other objects have following constructor :

public Object2() {
      super(SomeComponent.CORRESPONDING_ID);
   }

Do note that SomeComponent is a enum class.

So when I call newInstance() method, it works fine for every Object with constructor of type Object2 but in case of Object1 no instance is created.





Aucun commentaire:

Enregistrer un commentaire