I have a class which holds some colors for a GUI, which the program can change to its liking. For a specific element of the GUI, I’d like to be able to specify a color which is a member of that class. In C++, I could use something like
int Pallete::*color = &Pallete::highlight;
Pallete pallete; // made in or passed to the constructor
// ...
void draw() {
drawing.color(pallete.*color);
// ...
}
Is there an equivalent in java? I’ve thought about using getField(String) in the Class class, or keeping the colors in a Map with string keys, but neither of these seem like very good solutions, because they rely on strings, and the compiler can’t enforce that they are actually members of Pallete. I could also put all of the color names in an enum, and have some getter function which returns the associated color, but that seems like more work for me.
You could just use the
Integerclass. Since its a class, it obeys reference semantics.This would give you a class like
Edit
Okay, so the
Integerclass describes an immutable type, so you cannot change the value held by anInteger. The solution is pretty simple, though. You can just define your own, mutable class, like so:Of course, this example only provides the most basic functionality. You could always add more if you feel like it. You may also find it useful to use an internal
Integerrather than anint, or perhaps also to extend theNumberclass (as theIntegerclass does).If you declare
highlightandcolorto be ofMyIntegertype, and assignhighlighttocolor, then changes tohighlightwill be reflected incolor:One potential drawback of this method is that you cannot write an assignment like
Instead you must use
setValue()to change the value of an instance ofMyInteger. However, I don’t think this is a great loss, since it achieves the functionality you requested.