How to store the values of each variable of a class using a generic function?

user157629 :

I'm trying to store into an ArrayList all the values of each variable of a class. I have created this function in all the classes I have and I want it to do the same for each class (each class has different variables).

In other words, I want to @Override the toString function but without knowing how many attributes does the class have.

This is what I have done so far:

public class Example {

    private type1 var1 = 'Hello';
    private type2 var2 = 10;
    private type3 var3 = 'Bye';
    //...

    @Override
    public String toString() {
        ArrayList<String> fields = new ArrayList<>();

        for (Field f: this.getClass().getDeclaredFields()) {

            fields.add(f.getName());    //This does not work for what I want. This returns the name of the type of the variable and not what it is storing. What should I change it for?
        }

         return String.join(", ", fields);
     }
}

So, for this example, the output I get is:

var1, var2, var3

But the output I want is:

Hello, 10, Bye

Is there a way to do this?

Jocelyn LECOMTE :

You can get the value of the fields this way:

public class Example {

    private int var1;
    private String var2;
    private double var3;

    public Example(int var1, String var2, double var3) {
        this.var1 = var1;
        this.var2 = var2;
        this.var3 = var3;
    }

    @Override
    public String toString() {
        ArrayList<String> fields = new ArrayList<>();

        try {
            for (Field f: this.getClass().getDeclaredFields()) {
                fields.add(f.get(this).toString());
            }
        }
        catch(IllegalAccessException e) {
            return "Illegal access while generating toString";
        }

        return String.join(", ", fields);
    }
}

It should work well with primitive types. But of course it can get really messy (anyway when you use reflection, it's kinda messy from the start), if you want to manage complex types. I don't really know what you want to achieve but make sure reflection is your only option and double-check that you aren't reinventing the wheel.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=361620&siteId=1