views:

120

answers:

2

Say I have a class:

public class R {
    public static final int _1st = 0x334455;
}

How can I get the value of the field/property "_1st" via reflection?

+2  A: 
 R.class.getField("_1st").get(null);

Exception handling is left as an exercise for the reader.

Basically you get the field like any other via reflection, but when you call the get method you pass in a null since there is no instance to act on.

This works for all static fields, regardless of their being final. If the field is not public, you need to call setAccessable(true) on it first, and of course the SecurityManager has to allow all of this.

Yishai
thanks but it didn't help...
Viet
@Viet, can you clarify what didn't work about it? Perhaps post the code that you have that isn't working?
Yishai
Hi, the Exception e.getMessage() returns the field name, which is "_1st" and nothing else.
Viet
Hi Viet, what about the stack trace, and what is the type of the exception?
Yishai
I got it. The class I needed was actually R.id. Thanks for your help!
Viet
+1  A: 

First retrieve the field property of the class, then you can retrieve the value. If you know the type you can use one of the get methods with null (for static fields only, in fact with a static field the argument passed to the get method is ignored entirely). Otherwise you can use getType and write an appropriate switch as below:

Field f = R.class.getField("_1st");
Class<?> t = f.getType();
if(t == int.class){
    System.out.println(f.getInt(null));
}else if(t == double.class){
    System.out.println(f.getDouble(null));
}...
M. Jessup
thanks. I tried but it didn't work. Exception is thrown at the operation f.getInt(null). I caught it but how come there's an exception?
Viet
What kind of exception did you receive?
M. Jessup
Hi, the Exception e.getMessage() returns the field name, which is "_1st" and nothing else.
Viet
But what is the type of the exception? (i.e. NullPointerException, SecurityException, ...)
M. Jessup
I got it. The class I needed was actually R.id. Thanks for your help!
Viet