Search code examples
javalistarraylisttolist

Add all values of an instance of an object to a List


Say i have a class 'Dog' with a lot of String values and i want all of those values in a List, would there be any better way than adding every value by themselves?

e.g. take this dummy class, note that all values are Strings if that matters

public class Dog {
    private String breed;
    private String name;
    private String origin;
    [...] a lot more

    getter and setter methods
    }

Dog dog = new Dog([...] bla bla);

Would there be any better way to get all those values of an instance into a List than:

public List<String> toList() {
    List<String> list = new ArrayList<String>();
    list.add(dog.getBreed);
    list.add(dog.getName);
    list.add(dog.getOrigin);
    [...]
    return list;

Solution

  • you can use reflection.

    Dog dog = new Dog("val1", "val2", "val3");
                List<String> list = new ArrayList<>();
                for(Field field: Dog.class.getDeclaredFields()) {
                    // since fields are private we need to first mark it accesible
                    field.setAccessible(true);
                    if( field.getType().equals(String.class)) {
                            list.add((String) field.get(dog));
                    }
                }