Java-设置成员变量后,如何设置其他成员

时间:2019-07-16 00:00:00

标签: java spring spring-validator member-variables

我有以下旧代码,如下所示。我想知道在设置BikeGroup时是否可以设置BikeName和BikeModel?基本上,当用户设置BikeGroup时,我们如何自动设置Foo的BikeName和BikeModel版本?无需使用构造函数来设置值。我正在使用Validator(spring框架)设置BikeGroup ...因此我无法使用构造函数或setter来设置值。

Class Foo{
    private BikeGroup; // 1. when this is set
    private String bikeName; // 2. set this with value in BikeGroup
    private String bikeModel; // 3. and set this with value in BikeGroup
    //getters/setters
}

Class BikeGroup{
    private String bikeName;
    private String bikeModel;
    //getters/setters
}

1 个答案:

答案 0 :(得分:1)

是的。 但是Foo的构造函数必须命名为Foo(并且您想将BikeGroup传递给该构造函数,因此需要一个参数)。而且您不要将()放在class声明中。像

class Foo {
    public Foo(BikeGroup bg) {
        this.bikeName = bg.getBikeName();
        this.bikeModel = bg.getBikeModel();
    }
    private String bikeName;
    private String bikeModel;
}

,使用设置器...

class Foo {
    public void setBikeGroup(BikeGroup bg) {
        this.bikeName = bg.getBikeName();
        this.bikeModel = bg.getBikeModel();
    }
    private String bikeName;
    private String bikeModel;
}