Home > front end >  Dynamically read value of string array from constant in Java
Dynamically read value of string array from constant in Java

Time:12-16

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]

CodePudding user response:

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).

CodePudding user response:

[Ljava.lang.String;@47483 is simply toString on a String[].

You are retrieving the value correctly.

To use it, do:

public class App {

    private static final String[] car = {"Honda", "Toyota", "Volkswagen"};

    public static void main(String... args) throws NoSuchFieldException, IllegalAccessException {

        String needValueOf = "car";
        String[] xs = (String[]) App.class.getDeclaredField(needValueOf).get(null);
        System.out.println(xs);
        for (String x : xs) {
            System.out.println(x);
        }
    }
}

which prints:

[Ljava.lang.String;@41629346
Honda
Toyota
Volkswagen
  • Related