使用反射创建新对象?

JAN*_*JAN 20 java reflection constructor

给定类值:

public class Value {

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


    // constructor of the Value class 

    public Value(int _xVal1 ,int _xVal2 , double _pVal)
    {
        this.xVal1 = _xVal1;
        this.xVal2 = _xVal2;
        this.pVal = _pVal;
    }

    public int getX1val()
    {
        return this.xVal1;
    }


...
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用以下方法创建该类的新实例reflection:

来自Main:

    .... // some code 
    ....
    ....
    int _xval1 = Integer.parseInt(getCharacterDataFromElement(line));
    int _xval2 = Integer.parseInt(getCharacterDataFromElement(line2));
    double _pval = Double.parseDouble(getCharacterDataFromElement(line3));

     Class c = null;
     c = Class.forName("Value");
     Object o = c.newInstance(_xval1,_xval2,_pval);

...
Run Code Online (Sandbox Code Playgroud)

这不起作用,Eclipse的输出: The method newInstance() in the type Class is not applicable for the arguments (int, int, double)

如果是这样,怎么可以用我创建了一个新的价值目标reflection,在那里我调用ConstructorValue

谢谢

Mar*_*nik 40

您需要找到确切的构造函数.Class.newInstance()只能用于调用nullary构造函数.所以写

final Value v = Value.class.getConstructor(
   int.class, int.class, double.class).newInstance(_xval1,_xval2,_pval);
Run Code Online (Sandbox Code Playgroud)

  • 是的,我总是使用它,因为它使代码更容易阅读,让您高枕无忧,这个var在随后的代码中不会改变. (3认同)