使用反射创建新对象? [英] Create new object using reflection?

查看:147
本文介绍了使用反射创建新对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定类值:

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


...
}


$ b b

我试图使用反射

创建该类的新实例:

    .... // 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的输出: code>类型Class中的方法newInstance()不适用于参数(int,int,double)

This doesn't work , Eclipse's output : The method newInstance() in the type Class is not applicable for the arguments (int, int, double)

所以,如何使用反射创建一个新的Value对象,其中我调用构造函数的 Value

If so , how can I create a new Value object using reflection , where I invoke the Constructor of Value ?

感谢

推荐答案

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

You need to locate the exact constructor for this. Class.newInstance() can only be used to call the nullary constructor. So write

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

这篇关于使用反射创建新对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆