I have always wondered:
- If I a have for example 8 JLabels named label1, label2, label3…
- I receive a message to show in one of them and an integer number from 1 to 8
Is there any smart way to access the variable named label+number without using a switch or a bunch of if-elses? And if so, is it more efficient than the switch/if-elses method?
I’m labeling for Java, but I think it is an interesting question for any classic language.
you can use reflection for it, but it will suffer from bad performance, or you can do it using a
Map<Integer,JLabel>, which was precomputed with your objects.For the more general case, reflection is probably what you are looking for.
Simple example of the usage of reflection: