4

I have a class which has a bunch of Constant Strings.

I need to load this class via reflection and retrieve those constants. I can get up to:

controllerClass = Class.forName(constantsClassName);
Object someclass = controllerClass.newInstance();

but I am confused on how to retrieve the fields in this class.

Al-Punk
  • 3,531
  • 6
  • 38
  • 56
  • 1
    possible duplicate of [Accessing Java static final ivar value through reflection](http://stackoverflow.com/questions/850148/accessing-java-static-final-ivar-value-through-reflection) – Dave Newton Nov 14 '11 at 17:00
  • Two quick questions: 1. Are those constants private? 2. Are those constants static? – thkala Nov 14 '11 at 17:02

4 Answers4

5

A quick sample on accessing fields --

Field[] fields = controllerClass.getDeclaredFields();

for ( Field field : fields ) {
   field.setAccessible(true);
  System.out.println(field.get(someClass));

}
Kal
  • 24,724
  • 7
  • 65
  • 65
  • 1
    Just one catch to beware of: several classes, e.g. Boolean, have at least one static final Boolean member. That is, recursive definition. If you want to create a recursive 'class printer', be sure to check that !field.equals(parent) – Meymann Feb 19 '13 at 13:40
2

Assuming these constants are in static fields:

import java.lang.reflect.*;

public class Reflect {
  public static final String CONSTANT_1 = "1";
  public static final String CONSTANT_2 = "2";
  public static final String CONSTANT_3 = "3";

  public static void main(String[] args) throws Exception {
    Class clazz = Class.forName("Reflect");
    Field[] fields = clazz.getDeclaredFields();
    for(Field f: fields) {
      // for fields that are not visible (e.g. private)
      f.setAccessible(true);

      // note: get(null) for static field
      System.err.printf("%s: %s\n",f, (String)f.get(null) );
    }
  }
}

The output is:

$ java Reflect
public static final java.lang.String Reflect.CONSTANT_1: 1
public static final java.lang.String Reflect.CONSTANT_2: 2
public static final java.lang.String Reflect.CONSTANT_3: 3

Note that to get the value of a static field, you supply null as the arg.

Zaki
  • 6,997
  • 6
  • 37
  • 53
ewan.chalmers
  • 16,145
  • 43
  • 60
2

Here's a little sample:

import java.lang.reflect.Field;

public class Test {
    public static class X {
        public static int Y = 1;
        private static int Z = 2;

        public int x = 3;
        private int y = 4;
    }

    public static Object getXField(String name, X object) {
        try {
            Field f = X.class.getDeclaredField(name);

            f.setAccessible(true);

            return f.get(object);
        } catch (Exception e) {
            e.printStackTrace();

            return null;
        }
    }

    public static void main(String[] args) {
        System.out.println(Test.getXField("Y", null));
        System.out.println(Test.getXField("Z", null));

        System.out.println(Test.getXField("x", new X()));
        System.out.println(Test.getXField("y", new X()));
    }
}

Running this little program outputs:

1
2
3
4

A few observations:

  • For static fields the supplied object to Field.get() can be null.

  • For brevity, I used an exception catch-all with the base Exception class - you should use explicit exception classes in your code.

  • While Field.get() usually works as expected, the same cannot be said for Field.set() and its friends. More specifically it will happily change the value of a constant (e.g. a final field, or a private field that is never modified in the class methods), but due to constant inlining the old value may remain in use.

thkala
  • 84,049
  • 23
  • 157
  • 201
0

You get to know about the modifiers via the class and not the object reference.

http://download.oracle.com/javase/tutorial/reflect/class/classModifiers.html

Sid Malani
  • 2,078
  • 1
  • 13
  • 13