使用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对象,我在其中调用Value
的Constructor
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创建对象
- 如何将控制台输入传递给正在运行的Java程序而不是jdb?
- 在java中使用apache事件模型解析excel文件时,如何检查字符串中的数字包含日期和指数
- Java线程同步 – Thread.sleep()方法不按预期工作
- Java是通过值传递还是通过引用传递或两者兼而有之?
- Guava-11.0.2.jar与com.google.common_1.0.0.0_0-6.jar有冲突吗?
- 这个我正在制作动画的正方形背后留下了一条痕迹,任何人都可以找出原因吗?
- 如何比较JSON文档并返回与Jackson或Gson的差异?
- 在java中打印HTML文件
- 更好的理解 – Class.forName(“com.mysql.jdbc.Driver”)。newInstance();