【问题标题】:Java: How to reference a class var based on input?Java:如何根据输入引用类 var?
【发布时间】:2013-10-22 17:18:16
【问题描述】:

我有一个带有 4 个布尔值的“class Car”类:

class Car {
    boolean mWheel1 = true
    boolean mWheel2 = true
    boolean mWheel3 = true
    boolean mWheel4 = true
}

我还有一个方法“void removeWheel”,我只传递了1个参数,轮数:

void removeWheel(int wheelNum) {
    // I need help with the following line
    Car.mWheel(wheelNum) = false
}

最后一行是我需要帮助的地方。当我只将一个数字(1、2、3、4)传递给我的移除车轮方法时,如何在 Car 类中引用正确的“Car.mWheel”数字变量?

请记住,我可能会为我的汽车添加 100 多个轮子,因此我想动态连接对“Car.mWheel(wheelNum)”的引用,而不是执行一些 if 语句或静态解决方案。

【问题讨论】:

  • 用 if/else 语句...或者创建数组,这样会好很多。
  • switch 是另一种可能性。链接:docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
  • 这个例子尖叫“数组!使用数组!..”
  • 感谢您的评论,在这种情况下,我不想使用 4 个 if 语句,我想连接一个字符串,例如,如果我决定为我的汽车添加 25 个轮子。跨度>
  • if/else 更好的替代方法是使用大小为 4 的 boolean 数组。

标签: java string class parameter-passing concatenation


【解决方案1】:

这就是类的外观:

public class Car {

    private boolean[] wheels = new boolean[4];

    public Car() {
        for (int i = 0; i < 4; i++) {
            wheels[i] = true;
        }

    }

    public void removeWheel(int wheelNum) {
        getWheels()[wheelNum] = false;
    }

    /**
     * @return the wheels
     */
    public boolean[] getWheels() {
        return wheels;
    }

    /**
     * @param wheels the wheels to set
     */
    public void setWheels(boolean[] wheels) {
        this.wheels = wheels;
    }
}

【讨论】:

  • 我认为这个答案最接近 OP 的要求。
【解决方案2】:

代替

class Car {
    boolean mWheel1 = true
    boolean mWheel2 = true
    boolean mWheel3 = true
    boolean mWheel4 = true
}

void removeWheel(int wheelNum) {
    // I need help with the following line
    Car.mWheel(wheelNum) = false
}

class Car {
    boolean mWheel[4] = {true, true, true, true};
}

void removeWheel(int wheelNum) {
    mWheel[wheelNum] = false;
}

【讨论】:

    【解决方案3】:

    上面的数组是最好的选择,但是如果你想在不改变属性的情况下这样做:

    void removeWheel(int wheelNum) {
        switch (wheelNum) {
            case 1:
                mWheel1 = false;
                break;
            case 2:
                mWheel2 = false;
                break;
            case 3:
                mWheel3 = false;
                break;
            case 4:
                mWheel4 = false;
                break;
            default:
                break;
        }
    }
    

    【讨论】:

      【解决方案4】:

      是的,在这个简单的示例中,您希望为轮子使用数组或集合。但是通过名称动态访问属性可能是有正当理由的,您可以使用反射 API 来做到这一点:

      void removeWheel(int wheelNum) throws Exception {
          Car.class.getDeclaredField("mWheel" + wheelNum).setBoolean(this, false);
      }        
      

      【讨论】:

        猜你喜欢
        • 2017-03-27
        • 1970-01-01
        • 2022-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多