Given class Value :
public class Value {
private int xVal1;
private int xVal2;
private double pVal;
// constructor of the Value class
You need to locate the exact constructor for this. Class.newInstance()
can only be used to call the nullary constructor. So write
final Value v = Value.class.getConstructor(
int.class, int.class, double.class).newInstance(_xval1,_xval2,_pval);
The Class.newInstance()
method can only invoke a no-arg constructor. If you want to create objects using reflection with parameterized constructor than you need to use Constructor.newInstance()
. You can simply write
Constructor<Value> constructor = Value.class.getConstructor(int.class, int.class, double.class);
Value obj = constructor.newInstance(_xval1,_xval2,_pval);
For details you can read Creating objects through Reflection in Java with Example