反射:通过反射加载的类中的常量变量

时间:2011-11-14 16:54:43

标签: java reflection

我有一个有一堆常量字符串的类。

我需要通过反射加载这个类并检索这些常量。 我可以起床:

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

但我对如何检索此类中的字段感到困惑。

4 个答案:

答案 0 :(得分:5)

访问字段的快速示例 -

Field[] fields = controllerClass.getDeclaredFields();

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

}

答案 1 :(得分:2)

这是一个小样本:

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()));
    }
}

运行这个小程序输出:

1
2
3
4

一些观察结果:

  • 对于静态字段,Field.get()提供的对象可以是null

  • 为简洁起见,我使用了基类Exception类的异常catch-all - 您应该在代码中使用显式异常类。

  • 虽然Field.get()通常按预期工作,但Field.set()及其朋友也不能这样说。更具体地说,它将愉快地更改常量的值(例如,在类方法中从未修改过的final字段或private字段),但由于常量内联,旧值可能保留在使用

答案 2 :(得分:1)

假设这些常量在静态字段中:

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 visible (e.g. private)
      f.setAccessible(true);

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

输出结果为:

$ 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

请注意,要get静态字段的值,请提供null作为参数。

答案 3 :(得分:0)

您可以通过类而不是对象引用来了解修饰符。

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

相关问题