How to instantiante object & call setter on same line?

前端 未结 8 1287
一个人的身影
一个人的身影 2020-12-10 10:49

If I have an Employee class with a default constructor:

private String firstName;
public Employee(){}

and a setter:

         


        
8条回答
  •  情歌与酒
    2020-12-10 11:23

    In order for your code to work, you would have to return the Employee (meaning "this") in the setter method setFirstName.

    If you don't own the Employee class (I know this is just a simple example - but for the sake of argument) and cannot modify it, one way to solve that is using functional programming. You could declare yourself a function like this:

    static final Function EMPLOYEE = firstName -> {
            Employee employee = new Employee();
            employee.setFirstName(firstName);
            return employee;
    };
    

    And then you can create your employee in one line like this:

    Employee jake = EMPLOYEE.apply("Jake");
    

    Maybe not exactly what you want, but still useful.

提交回复
热议问题