dimanche 27 septembre 2015

Variable Reference Via String With Method Invocation In Java

I have been searching on here for several days and have come close to what I was hoping existed although not exactly.

I have a GUI that has a TabbedPane section containing several tabs that in turn have several JSpinners. The tabs are identical in structure and the spinners are named using the following naming convention [prefix]Spinner][num] (ex. Tab 1: redSpinner1, blueSpinner1.. Tab 2: redSpinner2, blueSpinner2.. and so on). I need to extract the values of the spinners on each tab and wanted to do it by "building" the variable name via concatenation of the prefix, "Spinner" and the incremented value that is the tab number that the spinner is located on. My goal is to not have to hard code the variable names yet still be able to access the variable methods, specifically getValue().

In my research I have come across two possible solutions:

1) Using a Map structure to map the variable name to the actual instance

2) Reflection API

The first method I can use my method of variable name concatenation for the key but will still have to manual map the instance variable name. Ultimately this puts me in the same position I am already in.

Full disclosure, I am not an expert in the reflection API, so I may not understand it sufficiently enough to solve my issue (hence why I am on here!). I have attempted/desire to do the following (or something close to it):

Class myClass = GuiClass.class; //GuiClass == main gui class containing spinners
Field myField = myClass.getField(redSpinner1); //using the 'built variable name'
int myValue = (int) myField.getValue(); //I can't get this step to work.

Any help would be greatly appreciated. I am beginning to think that I may have to change the design of that sections structure and want to see if anyone on SE has a better way. Thank you in advance.





Aucun commentaire:

Enregistrer un commentaire