Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dynamic variable names

 
Daniel Gallant
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 21129
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Replacing them with an array of the same type would be the simplest thing to do.
 
Daniel Gallant
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's what I thought.

Thank you for your help!

On a side note, is this even doable?
 
Paul Clapham
Sheriff
Posts: 21129
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 12146
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
IMHO, there is no need to do so. Variable names are for programmers, not the JVM.
 
Ralph Cook
Ranch Hand
Posts: 479
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
some1
3

But as java is compiled i think the reflection is the way to go.Refer http://www.coderanch.com/t/324748/java/java/Dynamic-Variable-naming-Java-at
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic