【问题标题】:Is there any way of calling sequential variable name in java in a for loop?有没有办法在for循环中调用java中的顺序变量名?
【发布时间】:2015-05-24 16:06:07
【问题描述】:

有没有办法在像matlab这样的for循环中调用java中的顺序变量名?例如我有像 c11,c12,c13 这样的变量名...有什么方法可以在 for 循环中调用它们,因为它们有共同的 c,然后名称部分是连续的?

【问题讨论】:

  • 这不是这样做的方法...将元素放在列表中并对其进行迭代。
  • 这就是数组或列表的用途。
  • 你想要一个类似字典的数据结构,比如HashMap吗?
  • 为什么 JTextFields 是这样命名的?这些字段也可以在一个数组中。

标签: java variables


【解决方案1】:

你可以使用反射(见Class.getDeclaredField(String):

MyTextFieldContainer container; // the object that contains the 81 JTextFields

Class<MyTextFieldContainer> containerType = container.getClass();

for (int 1 = 1; i <= 81; i++) {
    string fieldName = "textfield" + i.toString();
    Field fieldReflection = containerType.getDeclaredField(fieldName);
    Object fieldValue = fieldReflection.get(container);
    JTextField textfield = (JTextField)fieldValue;

    … // Use the JTextField however you like
}

检查Class&lt;T&gt;中的各种方法以选择适合您需求的方法:

  • getDeclared…()get…()
    • getDeclared…() 返回和字段/方法/等。在containerType 中声明的(即公共的、受保护的和私有的),它确实返回任何继承的字段/方法/等;
    • get…() 仅检索公共字段/方法/等。在containerType 中声明的以及从基类和接口继承的。
  • get…Field()get…Method()get…Constructor():分别返回字段、方法和构造函数。
  • get…s() vs. get…(String): getFields() 和类似方法返回类中所有字段(或方法或构造函数)的数组; getField(String) 返回命名字段(如果存在)。

【讨论】:

  • 我不推荐这种访问 JTextFields 的方法,但如果你必须这样做,你可以这样做。最好重新设计包含 81 个 JTextField 的类。
猜你喜欢
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
  • 2017-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多