• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Building a reference to a String

 
Bartender
Posts: 1757
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Say you want to build a reference to a string lower in your code based on some strings created higher in the code.
An example of what I mean is below. Say you create a few strings that vary only by the last character and you'd like to be able to build up these string names later in a for loop using the "test" prefix plus the for loop index.
What I'd like to be able to do is build a new string that references, say, test1 below, for example.
I'm not sure how to do this or if Java allows this, but my example is below.
Anybody's input would be appreacited.
String test1 = "AToyota";
String test2 = "A man a plan a canal panama";
String test3 = "Dad";
String test4 = "Mom";
String test5 = "Cat";
int i;

// want to build a String aString
// to "point" to test1 created above.
// want to build the string dynmaically.
String aString = ("test" + "1");
// this method (line of code above) doesn't
// work and just creates a new string aString,
// not a "pointer" to the test1 string created
// above.
if (pal1.isPalendrome(aString))
{
System.out.println("String " + aString + " is a palendrome");
}
else
{
System.out.println("String " + aString + " is not a palendrome");
}
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could use some reflection to do that.
Class.forName(classname).getDeclaredField(fieldname); /returns a Field object
So if you use:

This might work.
 
Mike London
Bartender
Posts: 1757
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wow, this is cool.
Thanks.
It might be easier to just use an array. <s>
-- Mike
 
Cindy Glass
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, yeah - but that only works if your Fields are constant. .
[ September 05, 2002: Message edited by: Cindy Glass ]
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should probably also take a look at java.util.Map
 
    Bookmark Topic Watch Topic
  • New Topic