Search code examples
javaeclipserad

Eclipse, short way to initialize object via setters


For example I have the following object:

public class Dog{
    private String name;
    private int age;
    private int legs;
    private Color color;

    /*getters and setters*/
}

And I want to initialize it and set all properties not by constructor but by using setters:

Dog dog = new Dog();
dog.setName("Rex");;
dog.setAge(4);
...

Can I generate code which set all fields from above in the easy way?


Solution

  • It's cumbersome, but what I do:

    Use Eclipse's Source -> Generate Getters and Setters... function (also ALT + SHIFT + S) and then just replace all '=' characters with '(' and ';' with ');'. finally I go through every line and press ctrl-space to let Eclipse finish the method call with proper casing (configure Eclipse to overwrite instead of insert code assist suggestions).

    That or do a regex replacement if it is a lot.