Since the array is a constant, simply make the array public and access it by name.
public class Constants{
public final static String[] car ={"Honda","Toyota", "Volkswagen"};
}
public class Main{
public static void main(String[] args){
String[] arr = Constants.car; // 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.
public class Constants{
private final static String[] cars ={"Honda","Toyota", "Volkswagen"};
private final static String[] boats = {...};
public static Map<String, String[]> myConstants = new HashMap<>();
public Constants () {
myConstants.put("cars", cars);
myConstants.put("boats", boats);
}
}
public class Main{
public static void main(String[] args){
String[] carsArr = myConstants.get("cars");
String[] boatsArr = myConstants.get("boats");
}
}
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).