code
code

Reputation: 55

How to convert a string variable value into a variable name

There are around 10 different types of 2D arrays of varied sizes. eg:

int arr1[][];
float arr2[][];
long arr3[][];
String arr4[][];

Each array needs to be printed at different intervals during the program execution. There is a method defined print2DArray() which takes the 2D array as parameter calculates the number of rows and columns and print the array. But since the arrays are of varied datatypes overriding methods need to be written for each data type.

Can we create a variable as: String arrName; and pass it to the method print2DArray() and decode the String to obtain the array to be printed. eg:

if method is called as: print2DArray(arr2);

and method is defined as:

void print2DArray(String arrName){
    **Some code to identify which array is reffered by arrName to print**
}

Upvotes: 0

Views: 2123

Answers (2)

swapyonubuntu
swapyonubuntu

Reputation: 2100

You need to use java reflection api for this purpose .

Code will be somewhat like this.

class CustomClass {
    int[][] arr1 = new int[][] { { 1, 2, 3, 4 }, { 5, 6, 8, 7 } };

    public static void main(String[] args) {
        CustomClass c = new CustomClass();

        Field[] f = c.getClass().getDeclaredFields();

        for (int i = 0; i < f.length; i++) {
            if (f[i].getName().equals("arr1")) {
                System.out.println(c.arr1[0][0]); // your own logic
            } else if (f[i].getName().equals("arr2")) {
                System.out.println(c.arr2[0][0]); // your own logic
            } else if (f[i].getName().equals("arr3")) {
                System.out.println(c.arr3[0][0]); // your own logic
            } else if (f[i].getName().equals("arr4")) {
                System.out.println(c.arr4[0][0]); // your own logic
            }
        }
    }
}

Upvotes: 1

Christophe Schutz
Christophe Schutz

Reputation: 613

I don't think you could do that natively. There's some easy workarounds though, the one i'd choose is to create a Map which contains all of your arrays linked with a key that would be the array name. That way, in your print2DArray function, you'd simply have to iterate your map and find the array that has the correct key (the one you give as a parameter in your function).

Your map would look something like this {"arr1", arr1}, {"arr2", arr2} etc... this would obviously force you to keep track of every newly created array by adding it in your Map (which isn't very costly anyways)

Upvotes: 0

Related Questions