Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

java - Create new object using reflection?

Given class Value :

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


...
}

I'm trying to create a new instance of that class using reflection :

from 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);

...

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

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

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...