Class clz= Class.forName("Test");
        Field f1 = clz.getField("LEN");
        ...下面怎么写,如果是非静态字段可以调用f1.getXXX(obj)方法取得
但取静态字段值就不用obj了

解决方案 »

  1.   

    get
    public Object get(Object obj)
               throws IllegalArgumentException,
                      IllegalAccessExceptionIf the underlying field is a static field, the obj argument is ignored; it may be null. 其他几种类型都可以直接用f1.getXXX(obj,比如:
    getBoolean
    public boolean getBoolean(Object obj)
                       throws IllegalArgumentException,
                              IllegalAccessException
    Gets the value of a static or instance boolean field.
      

  2.   

    我是这样用的啊System.out.println(f1.getInt(null));错误是java.lang.IllegalAccessException: Class amytest.TestStatic can not access a member of class Test with modifiers "public static"
    at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:57)
    at java.lang.reflect.Field.doSecurityCheck(Field.java:811)
    at java.lang.reflect.Field.getFieldAccessor(Field.java:758)
    at java.lang.reflect.Field.getInt(Field.java:369)
    at amytest.TestStatic.main(TestStatic.java:29)
    Exception in thread "main" 换成getDeclaredField也是一样的错误
      

  3.   

    import java.lang.reflect.*;public class Test
    {
    public static String name = "敏司令";

    public void setName(String name)
    {
    this.name = name;
    }

    public String getName()
    {
    return name;
    }

    public static void main(String[] args) throws Exception
    {
    Class clazz = Class.forName("Test");
    Field fld = clazz.getField("name");
    System.out.println(fld.get(null));
    fld.set(null,"司令");
    System.out.println(fld.get(null));
    }
    }
      

  4.   

    看API,上面说了static field 也是一样的方法