讨论/《Java 面试突击》 - 反射机制/
《Java 面试突击》 - 反射机制
共 1 个回复
import java.lang.reflect.*;
public class Test {
    public String string1 = "tutorial";
    public String string2 = "tutorial2";
    public static void main(String[] args) throws IllegalAccessException {
        Test t = new Test();
        Class cls = t.getClass();
        Field[] fields = cls.getFields();
        for(Field f:fields){
            System.out.println("field->"+f.toString());
            System.out.println("content->"+f.get(new Test()));
        }
    }
}

结果:

field->public java.lang.String Test.string1
content->tutorial
field->public java.lang.String Test.string2
content->tutorial2
12