danej klasy Wartość:Utwórz nowy obiekt za pomocą odbicia?
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;
}
...
}
Próbuję utworzyć nową instancję tej klasy przy użyciu reflection
:
od głównego:
.... // 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);
...
ten nie działa, wyjście Eclipse : The method newInstance() in the type Class is not applicable for the arguments (int, int, double)
Jeśli tak, w jaki sposób mogę utworzyć nowy obiekt wartości za pomocą reflection
, wh Czy mogę wywołać Constructor
z Value
?
Dzięki
Dzięki, działa świetnie! myślę jednak, jak teraz użyć obiektu Object? ponieważ jest to obiekt "Wartość", ale jest również obiektem Object. Więc po prostu użyj castingu, np. "Value currentValueNode = (Value) myObject;" ? – ron
Zobacz edytowaną odpowiedź. Kiedy zaczynasz od literału klasy zamiast 'Class.forName()', możesz wykorzystać generyczne. –
Marko, twoja nowa poprawka działa tylko bez "ostatecznego". dzięki ! – ron