1

Somebody knows or has an idea on how to simplify the code in getting the multiple variables from another class. Below are the structure of my program :

Data.java
//composed of 30 variables with almost the same variable name
String dat1 = "";
String dat2 ="";
.
.
.
String dat30="";

Get.java
//here, I need to get the variables from Data.java and put inside   the loop

for(int i=0; i<=30; i++) {
 String dat1 = getField(Data.dat1).getData();
}

Is there anyway to loop the dat1~dat30 variable from another class? Thank you in advance for those who will help ;)

exceptione
  • 101
  • 1
  • 18
  • 8
    Instead of creating 30 individual variables, create a `List` or array of `String`, the create a getter method that exposes it in the `Data` class. – azurefrog Apr 12 '17 at 15:55
  • Duplicate http://stackoverflow.com/questions/2466038/how-do-i-iterate-over-class-members – svenmeier Apr 12 '17 at 15:56
  • It is not a duplicate. What I am asking is there a way to simplify the code in getting the variables since the variable names are almost the same. I can't change the Data.java. I can only modify the Get.java. – exceptione Apr 12 '17 at 15:59

2 Answers2

3

You can use Java reflection API to read the values from Data object as shown below:

Data data = new Data();
//load data object with values

for(int i=1;i<=30;i++) {//iterate
   Field f = data.getClass().getDeclaredField("data"+i);//get each field
   f.setAccessible(true);
   System.out.println((String)f.get(data));//read value
 }

But, I strongly suggest you need to restructure the class so that it contains String[] data or List<String> data which will make things a lot easier.

Vasu
  • 21,832
  • 11
  • 51
  • 67
2

If it is possible to store the variables of Data class then instead of storing in 30 different variables like dat1, dat2, ... store those in an array like dat[30]. by doing this you can access the fields just by calling dat[i] in your loop.

But if it is not possible to store the fields other than different variable then you can use Class.getField method to get the field by name. In that case you can get the field by calling like getField("dat"+i).

stinepike
  • 54,068
  • 14
  • 92
  • 112