mercredi 6 octobre 2021

Instantiate object of given class by invoking implicit default constructor

Currently, I have a situation where I am trying to instantiate an object of a class, with the class given as a parameter, and have the object's properties initialized with default values (e.g. null). THe problem is, my class does not have any constructors and I am not able to add one for various reasons. The possible classes are also not connected by a superclass, they are all direct subclasses of Object. The classes I am trying to instantiate look like the following:

public class MyClass {
  public String prop1;

  public int prop2;

  public int prop3;
}

That means the classes contain only properties and no methods, and as such no explicit constuctors. In cases where I know the class beforehand, I can of course just do this:

public MyClass create() {
  return new MyClass();
}

In the above case, the compiler generates me a default constructor for MyClass and initiates all properties with their default values. As pointed out in the comments, this means I technically have a constructor, but one that I am only able to access using the "new" keyword and by knowing the class beforehand. Now, what I am trying to do (basically) is the following:

public someClass create(Class<?> someClass) {
  return new someClass();
}

Of course, the 'new' keyword won't work in this scenario, so I have tried out many alternatives, none of which have worked so far:

  1. Using someClass.getConstructor().newInstance() or someClass.getDeclaredConstructor().newInstance(). Code compiled but I got the expected "NoSuchMethodException" as it could not find an <init>-method or constructor for someClass
  2. Casting from Object like Object newObject = someClass.cast(new Object()). As expected, this crashes as well, as you can't cast from a superclass to a subclass

My only real alternative right now, as the range of possible classes is not too large, is to conjure up a massive switch-case using "instanceof"s for every class and then just using the "new" keyword in each branch. But as you can imagine, I am not too fond of that.

So am I trying to do the impossible or is there a way to do this?





Aucun commentaire:

Enregistrer un commentaire