mardi 13 mars 2018

get an instance of a class with variable number of arguments using Reflection

I have an Array that holds types:

myArray =[String.class,int.class,etc]

I have a class that has the parameter types as in myArray(same order,same number).

public class MyClass{
    MyClass(String a, int b, etc){
         **do something**
    }   
}

How can I invoke the constructor of the class, using myArray with getConstructor()? (if it is not possible with getConstructor(), how else can I achieve what I want?)

Something like this:

Constructor<?> constructor = SomeClass.getConstructor();
Class<?> newObject = (Class<?>) constructor.newInstance(myArray);

Note that SomeClass (in the example) reffers to the class MyClass.





Aucun commentaire:

Enregistrer un commentaire