有没有办法在for循环中调用java中的顺序变量名?

时间:2015-05-24 16:06:07

标签: java variables

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

1 个答案:

答案 0 :(得分:0)

You can use reflection (see 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
}

Check the various method in Class<T> to select the one that fits your needs:

  • getDeclared…() vs. get…():
    • getDeclared…() returns and field/method/etc. that is declared in containerType (i.e. public, protected, and private), it does not return any inherited fields/methods/etc.;
    • get…() only retrieves public fields/methods/etc. both those declared in containerType and those inherited from base classes and interfaces.
  • get…Field(), get…Method(), and get…Constructor(): return respectively fields, methods, and constructors.
  • get…s() vs. get…(String): getFields() and similar methods return an array of all fields (or methods or contructors) in the class; and getField(String) returns the named field, if it exists.