我有以下旧代码,如下所示。我想知道在设置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
}

最佳答案

是。但是,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;
}

10-05 17:44