给定类值:
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的输出:Class类型中的方法newInstance()不适用于参数(int,int,double)
如果是这样,如何使用 reflection
创建一个新的 Value 对象,并在其中调用 Value
的 Constructor
?
谢谢
最佳答案
您需要为此找到确切的构造函数。 Class.newInstance()
只能用于调用空构造函数。所以写
final Value v = Value.class.getConstructor(
int.class, int.class, double.class).newInstance(_xval1,_xval2,_pval);
关于java - 使用反射创建新对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10470263/