0

I have the following legacy code as shown below. I'm wondering is there a way to set BikeName and BikeModel when BikeGroup is being set? Basically, as the user is setting BikeGroup, how can we automatically set Foo's version of BikeName and BikeModel? Without using a constructor to set values. I'm setting the BikeGroup using a Validator (spring framework)... so I cannot use a constructor or setter to set the values.

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
}
hyperstack
  • 29
  • 1
  • 4
  • 1
    Classes are not declared with parentheses and variable names should start with a lower case character. Furthermore *"when this variable is set"* means nothing. As it stands right now, there is no way to set anything in your class because you have no constructors or methods. – RaminS Jul 16 '19 at 00:03
  • Sorry, you're right, they are CLASSES not constructors. – hyperstack Jul 16 '19 at 00:07
  • @hyperstack can you please publish your validator code and where it is used to assign the value for **BikeGroup**. Then somebody will be able to help you achieve what you try to do. – Johna Jul 16 '19 at 00:43
  • Possible duplicate of [Set and Get Methods in java?](https://stackoverflow.com/questions/6638964/set-and-get-methods-in-java) – Pavan Nath Jul 16 '19 at 03:14
  • You can look for some option using reflection. – Puneet Jul 16 '19 at 14:21

1 Answers1

1

Yes. But, the constructor for Foo must be named Foo (and you want to pass a BikeGroup to that constructor, so it needs a parameter). And you don't put () at class declaration. Something like,

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

Or, using a setter...

class Foo {
    public void setBikeGroup(BikeGroup bg) {
        this.bikeName = bg.getBikeName();
        this.bikeModel = bg.getBikeModel();
    }
    private String bikeName;
    private String bikeModel;
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • These are good answers, but I'm setting the BikeGroup using a Validator (spring framework)... so I cannot use a constructor or setter to set the values... – hyperstack Jul 16 '19 at 00:13
  • If you can't use a constructor and you can't use a method, then I think you're just out of luck. – Elliott Frisch Jul 16 '19 at 00:17