给定类值:
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
创建该类的新实例:
:
.... // 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对象,我在其中调用Constructor
的{{1}}?
谢谢
答案 0 :(得分:37)
您需要为此找到确切的构造函数。 Class.newInstance()
只能用于调用nullary构造函数。所以写
final Value v = Value.class.getConstructor(
int.class, int.class, double.class).newInstance(_xval1,_xval2,_pval);
答案 1 :(得分:1)
Class.newInstance()
方法只能调用no-arg构造函数。如果要使用带参数化构造函数的反射创建对象,则需要使用Constructor.newInstance()
。你可以简单地写
Constructor<Value> constructor = Value.class.getConstructor(int.class, int.class, double.class);
Value obj = constructor.newInstance(_xval1,_xval2,_pval);
有关详细信息,请参阅Creating objects through Reflection in Java with Example