126

Say I have a class:

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

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

Hearen
  • 7,420
  • 4
  • 53
  • 63
Viet
  • 17,944
  • 33
  • 103
  • 135

4 Answers4

153

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
  • 8,153
  • 1
  • 29
  • 29
89
 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 setAccessible(true) on it first, and of course the SecurityManager has to allow all of this.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Yishai
  • 90,445
  • 31
  • 189
  • 263
1

I was following the same route (looking through the generated R class) and then I had this awful feeling it was probably a function in the Resources class. I was right.

Found this: Resources::getIdentifier

Thought it might save people some time. Although they say its discouraged in the docs, which is not too surprising.

Brian
  • 79
  • 3
  • So you inferred it was an Android question. Should have been indicated in the tags... – Matthieu Apr 23 '15 at 15:03
  • It's not an Android question, it's a Java reflection question that uses a particular example. Questions are tagged based on their topic. – Matthew Read Dec 19 '16 at 17:05
1

I was looking for how to get a private static field and landed here.

For fellow searchers, here is how:

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

class ReflectionHacking {
    public static main(String[] args) {
        Field field = R.class.getFieldDeclaration("_1st");
        field.setAccessible(true);
        int privateHidenInt = (Integer)field.get(null);
    }
}
Valerij Dobler
  • 1,848
  • 15
  • 25