samedi 14 février 2015

Java reflection create instance of unknown class and constructor

I've already searched on Google and StackOverflow but I haven't found the answer yet..


I try to instantiate a class by name with constructor without knowing the types of the arguments of the constructor.



  1. I know the package and class name of the class (it is given to the method as string)

  2. I know the arguments of the constructor (they're also given to the method, but as an object array)


It has to be something similar to this:



// ... Load class using ClassLoader if not in classpath ...

// These are given as arguments to the function:
String pncn = "Some.Package.UnknownClass"; // packagename classname
Object[] oa =new Object[] {
"Test0",
new Random()
};///object array

Class cl = Class.forName(pncn);

Class[] ca = /* ? */;
// (Here I need to get all constructor argument classes by the objects in 'oa'

// Get the constructor with the given arg types of 'ca'
Constructor co = cl.getConstructor(ca);

//And then instantiate the class
Object ro = co.newInstance(ca) ;

/*//return it:
return ro;*/;


So basically the issue is how to transform the array of objects of different types ('oa' in the example) into an array of Class?


I plan to use this method to create instances of classes by name and arguments through javascript.






Aucun commentaire:

Enregistrer un commentaire