'How to make changes in class variables based on the value passed without using switch [duplicate]
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?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
