I want to read value of a string array constant dynamically.
Constant class has string array of car. NeedValueOf will dynamically append with constant name i.e Constants.needValueOf
Tell me the way to get value dynamic and after getting object i want value from that object. I want to get all the string array values in my method so that i can iterate and access the string car names
Class Constants{
Private final static String[] car ={"Honda","Toyota", "Volkswagen"};
}
Class Main{
Public static void main(){
String needValueOf ="car";
Constants.class.getDeclaredFields(needValueOf).get(null);
}
}
It is providing : [Ljava.lang.String;@47483]
Since the array is a constant, simply make the array public and access it by name.
Don't need to use reflection. 99.99% of the time, reflection is the worst choice you can make. The rest of the time is just a bad choice.
If the array wasn't constant, you can provide a getter method and create a defensive copy of the array. But that is out of scope based on your question.
UPDATE:
If "dynamic" is the main emphasis because there are many array constants and you want to access them by passing a
String, all you need is place them in a map.The map should not be
public static. It should not even be modifiable. All access should be controlled via methods. That way, you can control what is passed outside the class (i.e. a copy of the map).