Ken
Ken

Reputation: 3096

Java, get all variable values of a class

So I have a class called Test:

public class Test{
    protected String name = "boy";
    protected String mainAttack = "one";
    protected String secAttack = "two";
    protected String mainType"three";
    protected String typeSpeak = "no spoken word in super class";

//Somehow put all the class variables in an Array of some sort
    String[] allStrings = ??(all class' strings);
//(and if you feel challenged, put in ArrayList without type declared.
//So I could put in, not only Strings, but also ints etc.)

    public void Tester(){
    //Somehow loop through array(list) and print values (for-loop?)
    }
}

As you can see, I want to put all the class variables in an Array or ArrayList (or something similar) automatically. And next I want to be able to loop through the array and print/get the values. Preferably using an enhanced-for loop.

Upvotes: 0

Views: 4250

Answers (5)

geert3
geert3

Reputation: 7321

As other said, don't do this. But this is how:

Class<?> cl = this.getClass();
List<Object> allObjects = new ArrayList<Object>();
for (java.lang.reflect.Field f: cl.getDeclaredFields())
{
    f.setAccessible(true);
    try
    {
        Object o = f.get(this);
        allObjects.add(o);
    }
    catch (Exception e)
    {
        ...
    }
}
for (Object o: allObjects)
    System.out.println(o);

Upvotes: 1

DwB
DwB

Reputation: 38290

Do this.

String threeEleves = "sky";
String sevenDwarves = "stone";
String nineMortal = "die";
String oneRing[] = new String[]  // <<< This
{
  threeElves,
  sevenDwarves,
  nineMortal
}

or do this

// in some class.
public void process(final String... varArgs)
{
    for (String current : varArgs)
    {
    }
}

String one = "noodles";
String two = "get";
String three = "in";
String four = "my";
String five = "belly";

process (one, two, three, four, five);

Upvotes: 0

splrs
splrs

Reputation: 2432

Why not use a HashMap for the values and iterate through that?

Iterate through a HashMap

Upvotes: 0

rachana
rachana

Reputation: 3414

You can use Map or Hashmap to store variables and its values instead of Array or Arraylist

HashMap is an object that stores both “key/value” as a pairs. In this article, we show you how to create a HashMap instance and iterates the HashMap data.

Upvotes: 0

Tim B
Tim B

Reputation: 41168

If you really really need do this you need to use Reflection.

However a much better approach would be to store the values in a Map (probably a HashMap) and then you can query/set/etc them from that easily.

Upvotes: 0

Related Questions