【问题标题】:Create new object using reflection?使用反射创建新对象?
【发布时间】:2012-05-15 06:19:09
【问题描述】:

给定类值:

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 对象,并在其中调用 ValueConstructor

谢谢

【问题讨论】:

    标签: java reflection constructor


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,效果很好!想一想,我现在如何使用对象 Object ?因为它是一个“值”对象,但它也是一个对象对象。所以只需使用 cast ,例如“Value currentValueNode = (Value) myObject;” ?
    • 查看编辑后的答案。当您从类文字而不是 Class.forName() 开始时,您可以利用泛型。
    • Marko ,您的新修复仅在没有 "final" 的情况下有效。谢谢!
    • 什么意思? final 是可选的,当然,但我总是更喜欢使用它,因为大多数 vars 实际上是最终的(只分配一次)。稍后在代码中重新分配 v 吗?但这与这个问题无关。
    • 是的,我一直使用它,因为它让您放心,这个 var 不会在后面的代码中的任何地方发生变化,从而使代码更易于阅读。
    【解决方案2】:

    Class.newInstance() 方法只能调用无参数构造函数。如果您想使用带有参数化构造函数的反射创建对象,则需要使用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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      • 2015-07-30
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多