29

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

2 Answers 2

52

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);
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks ,works great! one think though , how do I use the object Object now ? since it is a "Value" object , but it's also an Object object . So just use casting , like "Value currentValueNode = (Value) myObject;" ?
See edited answer. When you start with the class literal instead of Class.forName(), you can leverage generics.
Marko , your new fix works only without the "final" . thanks !
What do you mean? final is optional, of course, but I always prefer to use it since most vars are in effect final (only get assigned once). Are you reassigning v later in the code? But that's unrelated to this problem.
Yes and I always use it because it makes code easier to read by giving you the peace of mind that this var is not going to change anywhere in the code that follows.
|
4

The Class.newInstance() method can only invoke a no-arg constructor. If you want to create objects using reflection with parameterized constructor than you need to use Constructor.newInstance(). You can simply write

Constructor<Value> constructor = Value.class.getConstructor(int.class, int.class, double.class);
Value obj = constructor.newInstance(_xval1,_xval2,_pval);

For details you can read Creating objects through Reflection in Java with Example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.