This question has multiple parts, and will all make sense in the last part:
-
Is it possible to programmatically list any programmer-defined variables in a Java class at runtime..?
I recently wrote a utility procedure in VB.Net that lists all the forms in my project by name, so I can pick one to run from a listbox (just for development purposes). With help from elsewhere on StackOverflow, I was able to pin the following bit of code together, and this example is pinned together even more for illustrative purposes...
System.Reflection.Assembly.GetExecutingAssembly().DefinedTypes(n).BaseType.FullName
Can something similar be done in Java to list variable names..? That being MyInteger, MyString, or MyObject, for example. It'd be like the function behind the "Locals" window in Visual Studio (but I'm using Eclipse for Java).
-
Somewhere in the past 20 years, in another programming language, I came across a function called Indirect(String varname). It was used to access a primitive variable by name. And the 'varname' parameter could itself be a variable; it didn't have to be a literal. Here's an example showing its use:
int N1, N2, N3; // N1, N2, & N3 are all zero for (int i = 1; i < 4; i++){ Indirect("N" + i.toString) = 100 } // N1, N2, & N3 are now all 100
Does Java have an equivalent to Indirect(), or is there a way to duplicate the same functionality..?
-
To glue all this together, and the reason for this entire forum post, is that I have the following procedure that I've written for debugging purposes, that I drop into my classes to output variable values in CSV format during development...
public String listVars(){ Object input[] = {var1, var2, var3, var4, var5}; // list of vars String output = ""; // output catcher int varCount = input.length; // get the length of the array for (int i = 0; i < varCount; i++){ // loop through the array output += "\"" + input[i] + "\""; // surround with quotes, append to output if (i < varCount-1){ // if the item NOT the last... output += ","; // append a comma to it } } return output; // return completed output }
-
What I would like to do is automate the input to the Object array with code that automatically enumerates the variables, so I don't have to copy & paste them into the function. And I'm assuming that in so doing, they would need to be referred to indirectly once their names are determined, so their values can be accessed in code.
PS - Filtering the variables by scope would be nice, such as 'private", 'super', , 'public', etc, but I know this may stretch it a bit too far. =-)
Aucun commentaire:
Enregistrer un commentaire