dcsimg
How to change Dynamicly variable name in java?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Laxman_Kande
Posted On:   Sunday, May 13, 2001 05:13 AM

I HAVE 30 VARIABLE TEST1 TO TEST30, NOW IN EACH VARIABLE I WANT TO ASSIGN SEPARATE VALUE USING LOOP LIKE FOR LOOP. I HAVE EXTRA VARIABLE CALLED "TEST". NOW HERE I AM USING

for (int i=1;i <=30; i++)
{
in this area i want the variable name should be change from test to test1..test30
test = something..
so how can i change variable name from test to test1 dynamically

}

thanks in advance..

Re: How to change Dynamicly variable name in java?

Posted By:   Michael_Wax  
Posted On:   Monday, May 14, 2001 09:58 PM

If you have 30 fields named test1 through test30, you might want to consider using an array, and naming your fields test[1]-test[30] (or test[0]-test[29]). If you really want dynamic naming, you could use reflection as follows (I am using doubles in this example):
import java.lang.reflect.Field;

public class YourClass {
double test1;
double test2;
...
public void yourMethod () {
...
for (int i=1; i<=30; i++}
Field f = this.getClass().getDeclaredField("test"+i);
field.setDouble(this,someValue);
}
}
}

Note that the reflection methods throw various exceptions that I am not bothering to catch here, and that there is considerable flexibility in the Field class to manipulate values of other than double fields.
About | Sitemap | Contact