如何使用反射?来获取getter的返回值?

时间:2012-05-07 02:23:59

标签: java xml dom reflection

给定圆形课程:

public class Round {

    private int roundNumber;
    private Door door1;
    private Door door2;

    public Round(int _roundNumber)
    {
        this.roundNumber = _roundNumber;
    }


    public void setRoundNumber(int _number) 
    {
        this.roundNumber = _number;
        this.door1 = null;
        this.door2 = null;
    }

    public int getRoundNumber()
    {
        return this.roundNumber;
    }
...

和Main中的代码:

Round[] gameRounds;  

// manipulations on gameRounds , assume that we put some data into array gameRounds 

...
...
Object ret = null;
for (int i = 0; i < gameRounds.length; i++)
{

    Method roundFunction = Round.class.getMethod("getRoundNumber", new Class[] {});
    ret = roundFunction.invoke(gameRounds[i]);
    // need to put something here 
}

我正在尝试使用反射检索字段roundNumber,但返回值是对象类型,如何使用其值,即如何将其转换为int roundNumber?我需要把它写成一个新的XML文件......

谢谢

1 个答案:

答案 0 :(得分:2)

返回值为Integer。将其投放到Integer,然后让自动拆箱处理它。