0
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. I have to call both nullary constructor and non nullary constructor.

  • Why are you using `field.getType().newInstance()` instead of `field.get(someClass)`? – Holger Oct 02 '19 at 13:26
  • Possible duplicate of [Can I use Class.newInstance() with constructor arguments?](https://stackoverflow.com/questions/234600/can-i-use-class-newinstance-with-constructor-arguments) – Elias Oct 02 '19 at 13:33
  • I am new to java. Thanks that worked :) @Holger – suyog surana Oct 02 '19 at 13:36

1 Answers1

0

Please provide the complete code and the error.

I think that the super class or the class of the first object doesn't have a constructor with empty parameters.

Ashis Roy
  • 44
  • 4
  • That's what I asked in the question. If two different constructors have to called, how should I do that. @Holger provided the right solution to me. – suyog surana Oct 05 '19 at 03:05