reflection:通过reflection加载的类中的常量变量

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

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

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

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

访问字段的快速示例 –

 Field[] fields = controllerClass.getDeclaredFields(); for ( Field field : fields ) { field.setAccessible(true); System.out.println(field.get(someClass)); } 

这是一个小样本:

 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类的exceptioncatch-all – 您应该在代码中使用显式exception类。

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

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

 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 (eg 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 

请注意,要获取静态字段的值,请提供null作为arg。

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

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