Re: How to: referencing variables using the contents of otehr variables.
fguy64s@gmail.com wrote:
Is there a way to reference a variable using the contents of another
variable?
It depends on what you exactly mean by this question:
* Is it possible to have a reference to a class variable (static or
instance)?
Yes, via reflection. However, this is probably the wrong thing to do
for most cases. Avoid this method unless it would be completely
untenable to avoid (think something akin to serialization).
* Is it possible to have a reference to a local variable?
Not really.
* Is it possible to have outparams?
Not directly, but passing in mutable types and changing them in the
callee comes close. Having a one-length array parameter is the most
common emulation of this feature.
I have a variable, primitive data type char, that can contain many
different values. For each of these values, there is a corresponding
array of the same name as the contents of the char variable.
My internal alarm is screaming "use a hash table (HashMap)" at this
statement. Well, actually, if it's dense enough, you could just have a
single value array:
String K[][] = ...;
String data[][][] = new String[26][][[];
data['K'-'A'] = K;
Lew gave you a rough idea of how to use Maps to achieve the same means,
so I won't repeat him there. I don't think the outparam information
would be useful for you, and I prefer to eschew explaining the
reflection method since it's almost certainly a hammer for your screw.
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth