5

How to retrieve a static variable using its name dynamically using Java reflection?

If I have class containing some variables:

public class myClass { 
     final public static string [][] cfg1= {{"01"},{"02"},{"81"},{"82"}}; 
     final public static string [][]cfg2=  {{"c01"},{"c02"},{"c81"},{"c82"}}; 
     final public static string [][] cfg3=  {{"d01"},{"d02"},{"d81"}{"d82"}}; 
     final public static int cfg11 = 5; 
     final public static int cfg22 = 10; 
     final public static int cfg33 = 15; 
 }

And in another class I want variable name is input from user:

class test { 
   Scanner in = new Scanner(System.in); 
   String userInput = in.nextLine();  
    // get variable from class myClass that  has the same name as userInput
   System.out.println("variable name " + // correct variable from class)
}

Using reflection. Any help please?

0

5 Answers 5

4

You need to make use of java reflect. Here is a sample code. For example, I accessed 'cfg1' variable using java reflection, and then printed it into the console. Look into the main method carefully. I have handled no exceptions for simplification. The key line here is:

(String[][]) MyClass.class.getField("cfg1").get(MyClass.class);

__ ^typecast__ ^accessingFeild______________ ^accessFromClassDefinition

public class MyClass {
    final public static String[][] cfg1 = { { "01" }, { "02" }, { "81" },
            { "82" } };
    final public static String[][] cfg2 = { { "c01" }, { "c02" }, { "c81" },
            { "c82" } };
    final public static String[][] cfg3 = { { "d01" }, { "d02" }, { "d81" },
            { "d82" } };
    final public static int cfg11 = 5;
    final public static int cfg22 = 10;
    final public static int cfg33 = 15;

    public static void main(String[] args) throws IllegalArgumentException,
            IllegalAccessException, NoSuchFieldException, SecurityException {

        String[][] str = (String[][]) MyClass.class.getField("cfg1").get(
                MyClass.class);

        for (String[] strings : str) {
            for (String string : strings) {
                System.out.println(string);
            }
        }

    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

If I well understood your needs, this could suit them:

// user input, hardcoded for the example
String fieldName = "cfg22";

MyClass blank = new MyClass();
Object value = null;
try {
    value = MyClass.class.getDeclaredField(fieldName).get(blank);
} catch (IllegalArgumentException e) {
    // if the specified object is not an instance of the class or
    // interface declaring the underlying field (or a subclass or
    // implementor thereof)
    e.printStackTrace();
} catch (SecurityException e) {
    // if a security manager, s, is present [and restricts the access to
    // the field]
    e.printStackTrace();
} catch (IllegalAccessException e) {
    // if the underlying field is inaccessible
    e.printStackTrace();
} catch (NoSuchFieldException e) {
    // if a field with the specified name is not found
    e.printStackTrace();
}

System.out.println(value);

Prints 10.

8 Comments

thanks for your help but this doesn't work with me note : my variables is final public static is that the reason that it doesn't work ??
This code doesn't work for static fields, becasue the argument to Field.get() is incorrect for statics. Also no loop is required here. -1 @user2538438 There are no final public statics in the code you posted.
ok , sorry for my mistake but I want them final public static so , any help please ??
@user2538438 Have you considered looking up the Javadoc for Field.get() to see what the argument should be?
ok , It works now after I did casting Thanks alot for your help
|
1

I merge the two above solutions and get:

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;

public class MyClass
{

final public static String[][] cfg1 = {{"01"}, {"02"}, {"81"},
{"82"}};
final public static String[][] cfg2 = {{"c01"}, {"c02"}, {"c81"},
{"c82"}};
final public static String[][] cfg3 = {{"d01"}, {"d02"}, {"d81"},
{"d82"}};
final public static int cfg11 = 5;
final public static int cfg22 = 10;
final public static int cfg33 = 15;

public static void main(String[] args) throws IllegalArgumentException,
        IllegalAccessException, NoSuchFieldException, SecurityException
{

    for (Field field : MyClass.class.getDeclaredFields()) {
        if (!Modifier.isStatic(field.getModifiers())) {
            System.out.println("Non-static field: " + field.getName());
        }
        else {
            System.out.println("Static field: " + field.getName());
            Object obj = MyClass.class.getField(field.getName()).get(MyClass.class);
            if (obj instanceof String[][]) {
                String[][] cad = (String[][]) obj;
                for (String[] strings : cad) {
                    System.out.println("Values:: " + Arrays.toString(strings));
                }
            }
            else {
                System.out.println("  " + obj.toString());
            }
        }
    }

}
}

Comments

0

You can try something like this :

for (Field field : myClass.class.getDeclaredFields()) {
    if (!Modifier.isStatic(field.getModifiers())) {
        System.out.println("Non-static field: " + field.getName());              
    }
    else {
        System.out.println("Static field: " + field.getName());
    }
}

Use Field#get(Object obj) to get the value .

Note: Please follow Java naming conventions.

2 Comments

I want the value of modifier not the name (i.e. I want the value of array name entered by user and access the element [0][0] in it )
sorry for bothering but I try this code and give me an exception Field f = s.getClass().getDeclaredField(VariableName); String ss[][]=null; f.get(ss); System.out.println(f.getName() + " = " + ss[0][0]); I want to retrieve the value of a 2D array in myClass s
0

Just call Class.getField() or Class.getDeclaredField(), then call Field.getValue() on the result, providing null (or the class itself) as the parameter in the case of a static variable, or an instance of the class in the case of an instance variable.

1 Comment

You should rather give null as parameter if you want to access a static field. The parameter is simply ignored.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.