aspose file tools*
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 Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Dynamic variable names" Watch "Dynamic variable names" New topic
Author

Dynamic variable names

Daniel Gallant
Greenhorn

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
Bartender

Joined: Oct 14, 2005
Posts: 18657
    
    8

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

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
Bartender

Joined: Oct 14, 2005
Posts: 18657
    
    8

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

Joined: Oct 02, 2003
Posts: 11411
    
  16

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
Greenhorn

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
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Dynamic variable names