How to access all variables of a single class?


#1

Say, for example, I have this class:

class thing{
  float x;
  float y;
  String z;
  String w;
  boolean omega;
  int foo;
  thing(){} //A meh constructor, I know. ._.
}

And I want to repeat a specific set of code on all float variables in the class, and then another with all string variables.
One thing I can do for this is simply manually repeat that piece of code for every float and every string, considering that I know all of them: doThing(thatThing.x); doThing(thatThing.y); doStringThing(thatThing.z); ...
But, this means that if I’ll add or remove variables from this class, I’ll also have to edit this line of doThing() calls to fit the new contents. And I don’t like repeating stuff in this fashion, so I’m wondering - is there a way to do this any better?

One way that I did consider is making a 1 row long Table instead of a new class, store everything inside of that, and then use getColumnTitles() to get a list of all “variables” in there - however that is significantly slower than having these variables the normal way. Or a JSONObject using the same methods - except it doesn’t have getColumnTitles() and has an iterator instead - but with this usage it’s almost the same thing and still shows poor performance.

Any ideas?


#2

I think you need to provide some code. I do not get your question with the information you provided.

Kf


#3

You have a class ‚Thing‘ with 10 int variables and 5 Strings and some others. Now he wants to know if there is a way to access all ints because he doesn‘t want to changed them manually When he changes them inside the class. Like

((Thing)thing).getAllInts(); //returns all int variables in the class. 

Oh and he probably doesn‘t want to have it as a new method like

int[] getAllInts() {
  int[] ret = new Int[10];
  ret = append..... and then just append each int
  return ret;
}

because Then he has to edit this method, which is the Same as just editing the normal code…


#4

Well, you could group all your variables by type.

class thing{
  float[] xy = new float[2]; // xy[0] is x, xy[1] is y
  String[] zw = new String[2];
  boolean omega;
  int foo;
  thing(){} //A meh constructor, I know. ._.
  void doThingForAllFloat(){
    for( int i = 0; i < xy.length; i++){
      xy[i] = do_thing( xy[i] );
    }
  } 
}

Does that make any sense? It’s actually more confusing if you ask me…


#5

It does make sense, and it pretty much answers the question - however it also means dealing with arrays, and remembering what is what in those arrays, so I’ll just stick to manual repeating, actually. I think I’ll remember to change everything I need if I change the class’s insides.

Thanks for the responses though!


#6

Sorry, there is just no practical way to do it. Though some Programms do this automatically, like eclipse.