Create new object using reflection?

后端 未结 2 1104
梦毁少年i
梦毁少年i 2020-12-03 05:18

Given class Value :

public class Value {

    private int xVal1;
    private int xVal2; 
    private double pVal;


    // constructor of the Value class 

         


        
相关标签:
2条回答
  • 2020-12-03 05:25

    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);
    
    0 讨论(0)
  • 2020-12-03 05:46

    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

    0 讨论(0)
提交回复
热议问题