This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Dynamic variable names Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Dynamic variable names" Watch "Dynamic variable names" New topic

Dynamic variable names

Daniel Gallant

Joined: Sep 09, 2009
Posts: 27
Here is my situation:

I am maintaining an old program and I have a situation where I have a group of objects named item1, item2, item3, etc. with a .doStuff() method.

Is there a way to build a call to those items so I can do something like this:

I think this is possible but I have no clue how.

Thanks, as always!
Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

Replacing them with an array of the same type would be the simplest thing to do.
Daniel Gallant

Joined: Sep 09, 2009
Posts: 27
That's what I thought.

Thank you for your help!

On a side note, is this even doable?
Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

Daniel Gallant wrote:On a side note, is this even doable?

Based on the code I have seen, I would have to say "Maybe".
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11956

IMHO, there is no need to do so. Variable names are for programmers, not the JVM.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Ralph Cook
Ranch Hand

Joined: May 29, 2005
Posts: 479
You can use Java reflection (java.lang.reflect.*) to obtain the names of all the variables, and refer to them by name. I'm not sure why you would want to, but that's the java feature that enables that kind of manipulation.

I would be more interested in Eclipse's feature to change all the uses of one name of a variable to something else, throughout a project.

Ganesh Malaichamy

Joined: Feb 11, 2011
Posts: 27
Dynamic varaibles are used in some interpreted languages like tcl where all the variables are treated as type independent.

set a 1
set b 2
set c some$a
puts $c
set d [expr $a + $ b]
puts $d

Ouput will be

But as java is compiled i think the reflection is the way to go.Refer
I agree. Here's the link:
subject: Dynamic variable names
It's not a secret anymore!