问题
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.
回答1:
A quick sample on accessing fields --
Field[] fields = controllerClass.getDeclaredFields();
for ( Field field : fields ) {
field.setAccessible(true);
System.out.println(field.get(someClass));
}
回答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 benull.For brevity, I used an exception catch-all with the base
Exceptionclass - you should use explicit exception classes in your code.While
Field.get()usually works as expected, the same cannot be said forField.set()and its friends. More specifically it will happily change the value of a constant (e.g. afinalfield, or aprivatefield that is never modified in the class methods), but due to constant inlining the old value may remain in use.
回答3:
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.
回答4:
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
来源:https://stackoverflow.com/questions/8125086/reflection-constant-variables-within-a-class-loaded-via-reflection