Hi there,
I dont seem to be able to find the answer to this anywhere, so I am
wondering if anyone can help me. I am trying to see if there is a way of
referencing a object dynamically by passing it a variable.
For instance say I have an object called 'myObject', which contains
a public method called 'getTotal()'.
I also have a string variable called 'objectName', which contains
the string "myObject".
Is there a way of referencing 'myObject' using the contents of the
string variable. So is there a way to get the following line of code, or
something equivalent, to work:
objectName = "myObject";
objectName.getTotal();
Ive tried casting 'objectName' but that doesnt work, does anyone have
any suggestions?
Mike Schilling - 18 Jan 2006 19:18 GMT
> Hi there,
> I dont seem to be able to find the answer to this anywhere, so I am
[quoted text clipped - 8 lines]
> Is there a way of referencing 'myObject' using the contents of the
> string variable.
No. Local variable names are not known at runtime.
Gordon Beaton - 18 Jan 2006 19:21 GMT
> I dont seem to be able to find the answer to this anywhere, so I am
> wondering if anyone can help me. I am trying to see if there is a
> way of referencing a object dynamically by passing it a variable.
Your question is asked (and answered) here on a regular basis.
> Ive tried casting 'objectName' but that doesnt work, does anyone
> have any suggestions?
Casting doesn't do magic. Store your object reference in a HashMap,
using the Strings as keys.
/gordon

Signature
[ do not email me copies of your followups ]
g o r d o n + n e w s @ b a l d e r 1 3 . s e
isamura - 18 Jan 2006 19:27 GMT
: Hi there,
: I dont seem to be able to find the answer to this anywhere, so I am
[quoted text clipped - 16 lines]
: Ive tried casting 'objectName' but that doesnt work, does anyone have
: any suggestions?
I suspect this is not the correct approach regardless of language. A more realistic solution is to
store the actual object, myObject in a Hash ('myObject' -> myObject). Then you can use Hash.get()
with 'myObject' string to get at it.
.k
isamura - 18 Jan 2006 19:37 GMT
: : Hi there,
: : I dont seem to be able to find the answer to this anywhere, so I am
[quoted text clipped - 22 lines]
:
: .k
I must have been thinking about Hasheesh...I really mean Map...
.k