Al-Punk
Al-Punk

Reputation: 3660

Reflection: Constant variables within a class loaded via reflection

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.

Upvotes: 4

Views: 7876

Answers (4)

ewan.chalmers
ewan.chalmers

Reputation: 16235

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.

Upvotes: 2

thkala
thkala

Reputation: 86333

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.

Upvotes: 2

Kal
Kal

Reputation: 24910

A quick sample on accessing fields --

Field[] fields = controllerClass.getDeclaredFields();

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

}

Upvotes: 5

Sid Malani
Sid Malani

Reputation: 2116

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

Upvotes: 0

Related Questions