有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用getter的返回值,使用反射?

给定班级轮数:

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

和主要代码:

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) 个答案

  1. # 1 楼答案

    返回值将是一个Integer。将其强制转换为Integer,然后让自动取消装箱处理它