Is there any way of calling sequential variable name in java in a for loop like matlab? For example I have variable names like c11,c12,c13... Is there any way i can call them in a for loop as they have c in common and after that the name parts are sequential?
Asked
Active
Viewed 507 times
-1
-
1That's not the way to do it... Put the elements in a list and iterate them. – Nir Alfasi May 24 '15 at 16:10
-
4That's what arrays or lists are made for. – runDOSrun May 24 '15 at 16:11
-
Do you want maybe a dictionary-like data structure, such as HashMap? – nbro May 24 '15 at 16:20
-
Possible duplicate: http://stackoverflow.com/questions/17095628/loop-over-all-fields-in-a-java-class. – diogo May 24 '15 at 16:21
-
For this reason you should use Array or ArrayList whichever is compatible or useful according to your need. Just Assign an Array with some variable name let's call **c** and then iterate in the loop with **c[position]**. This will work as like what you are dealing with. – Suraj Palwe May 24 '15 at 16:39
-
Thanks a lot..for the response. But i need to take input from 81 JtextFields which are named like these. Thats why ineeded that. Thanks a lot for your response. – Shahreen Shahjahan May 24 '15 at 17:47
-
1Why are the JTextFields named like that? These fields could also be in an array. – Kasper van den Berg May 24 '15 at 20:04
1 Answers
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 incontainerType
(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 incontainerType
and those inherited from base classes and interfaces.
get…Field()
,get…Method()
, andget…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; andgetField(String)
returns the named field, if it exists.

Kasper van den Berg
- 8,951
- 4
- 48
- 70
-
I do not recomment this method of accessing the JTextFields, but if you have to you can do it. It's better to redesign your class that contains the 81 JTextFields. – Kasper van den Berg May 24 '15 at 20:29