• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to get object reference using String

 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I would like to know if its possible to get a reference to an object without using an array. For example, lets say this code declares a 3 Integaer3:

Integer a = new Integer(1);
Integer b = new Integer(2);
Integer c = new Integer(3);

Instead of using:

System.out.println(a);
System.out.println(b);
System.out.println(c);

I want to output the same using the Strings "a", "b", "c". Can I get the object references using "a", "b" and "c". ?

Is that possible?
 
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
System.out.println calls an object's toString() method for display. So you can discover what would be printed by using:

....etc. But many classes override the toString() method, so this is not guaranteed to give you the 'object reference', just what would be printed out by System.out.println.
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think you may be asking about a map. The Map interface lets you store an object with a key and retrieve it by key later. A string makes a fine key, but any other object can be a key as well.
 
Bartender
Posts: 1205
22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Or you could make the variables instance fields (i.e. NOT defined inside a method) and then use java.lang.Class and the classes in java.lang.reflect to get at them. Look at Class.getField(String).

Ryan
[ May 04, 2005: Message edited by: Ryan McGuire ]
 
reply
    Bookmark Topic Watch Topic
  • New Topic