有没有一种方法可以遍历类中的每个实例变量?

时间:2020-08-26 15:36:48

标签: java loops oop variables tostring

我目前正在尝试编写一个将字符串与所有实例变量进行比较的类,如果该字符串等于实例变量的名称,则应为此实例变量设置一个值(int)。顺便说一下,所有实例变量都是int。

public void set(String st, int zahl){
    if(st.equals("ab")){
        this.ab = zahl;
    }
    if(st.equals("a")){
        this.a = zahl;
    }
    if(st.equals("b")){
        this.b = zahl;
    }

这是我的操作方式,但是我真正想做的是:

public void set(String st, int number){
    for( every instance variable : class){
        if(instanceVariable.toString().equals(st)){

            instanceVariable = number;
            break;
        }
    }
}

有办法吗?预先感谢!

0 个答案:

没有答案