mardi 4 avril 2017

Create object using Java reflection

I receive from an external source strings that are pretty much the signature of the constructor of the object. They contain the class name and the parameters.

For example:

public class Foo {
 public Foo(int x, int y, int z) {
// do something
}
}

public class Bar {
public Bar (int x, boolean bool) {
// do something
}
}

Let's say I have many classes like this, and I want to create object from these classes based on the string I receive (that contains the class name and the paramters). Can this be done?

I know I can get the class using something like this:

String className = "myClass";
Class<?> myClass = Class.forName(className);
//Constructor<?> ctor = myClass.getConstructor();
//Object object = ctor.newInstance(new Object[] { ctorArgument });

But how can I instantiate the object if I don't know at compile time how many paramters the constructor will have and of which type they will be? By the way, the classes from which I want to create the object will most likely have only one constructor available. But each class might have a different constructor compared to the other.





Aucun commentaire:

Enregistrer un commentaire