使用reflection创建新对象?

给定类值:

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; } ... } 

我正在尝试使用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); ... 

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

如果是这样,我如何使用reflection创建一个新的Value对象,我在其中调用ValueConstructor Value

谢谢

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

 final Value v = Value.class.getConstructor( int.class, int.class, double.class).newInstance(_xval1,_xval2,_pval); 

Class.newInstance()方法只能调用无参数构造函数。 如果要使用带参数化构造函数的reflection创建对象,则需要使用Constructor.newInstance() 。 你可以简单地写

 Constructor constructor = Value.class.getConstructor(int.class, int.class, double.class); Value obj = constructor.newInstance(_xval1,_xval2,_pval); 

有关详细信息,请参阅使用示例通过Java中的reflection创建对象