解决方案 »

  1.   

    public static void main(String[] args) {
    try {
    Person p1= (Person) Class.forName("Person").newInstance();
    Field f = p1.getClass().getDeclaredField("age");
    System.out.println(f.get(p1));

    } catch (InstantiationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (NoSuchFieldException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
      

  2.   

    可以加一句
    f.setAccessible(true);
      

  3.   

    非常感谢二楼。我试的时候没有加newInstance();  所以一直不行
      

  4.   

    Class<?> cache = Integer.class.getDeclaredClasses()[0];
            System.out.println(cache);
            Field c = cache.getDeclaredField("cache");
            c.setAccessible(true);
            Integer[] array = (Integer[]) c.get(cache);看看这个 这个为啥是 c.get(cache);  cache是一个Class类型您的代码  f.get(p1)   p1是一个Person类型 
    Class<?> s= Person.class;
    因为上面的代码 我一直 f.get(s)
      

  5.   

     
    传入class 类型获取静态 类变量
      

  6.   

     恩  果然是。如果不是static 。必须 实例化才能反射。对吗?