jeudi 26 mars 2020

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

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?





Aucun commentaire:

Enregistrer un commentaire