-1

Let's say I have following class:

@Getters
public class Metrics {
    private String length;
    private String width;
    private String height;
    private String volume;

    public void changeMetric(string newValue, string metricVariable) {
       /*
         based on metricVariable value (which can be "length", "width", "height" or "volume")
         change the corresponding private variable with the newValue.
       */
    }
}

changeMetric can be implemented using switch case, however it would take lot of code incase the number of private variables is large.

Is there any annotation, framework or other solution, which can directly change the corresponding private metricVariable without iterating to each one of them?

Cactusroot
  • 1,019
  • 3
  • 16
laser
  • 87
  • 1
  • 8
  • 2
    use a HashMap instead of individual data members. – OldProgrammer Apr 27 '22 at 17:41
  • @OldProgrammer yes it can be one of the solutions however we need to use different logic for fetching the values (instead of using Getters annotation). – laser Apr 27 '22 at 17:43
  • If you must have named variables (instead of an addressable collection) for the attributes, then you're stuck with `switch` or `if-then-else`. It's not really clear what you're after here. – Jim Garrison Apr 27 '22 at 17:45
  • @JimGarrison won't switch case or if-else requires multiple lines of code ? that is what i want to reduce. – laser Apr 28 '22 at 10:11

1 Answers1

2

There is no direct way of doing that, because the String metricVariable you transfer is just an array of characters, nothing else. You should absolutely not use switch-case, as you explicitly have to connect each variable to the corresponding String.

A Map<String, ?> is for mapping any arbitrary String (name) to a corresponding value, but as your values are clearly defined, this is not a solution for this case.

You can make your attributes public if you want them to be changed from everywhere.

To have more control over what is happening with your attributes, you can use getters and setters.

Using a String to reference your attributes (variables) is bad style, but you can do it using reflection:

public void changeMetric(String newValue, String metricVariable) {
    Metrics.class.getDeclaredField(metricVariable).set(this, newValue);
}

Note:

String is a class and thus has to start with an uppercase s.

Cactusroot
  • 1,019
  • 3
  • 16
  • "There is no direct way", I mentioned in problem: "Is there any annotation or framework or any other solution with help of which we can directly change the corresponding private metricVariable without iterating to each one of them.". If reflection works then that's what I wanted ! – laser Apr 28 '22 at 10:20