反射简单问题 class反射简单问题 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 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(); } } 可以加一句 f.setAccessible(true); 非常感谢二楼。我试的时候没有加newInstance(); 所以一直不行 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) 传入class 类型获取静态 类变量 恩 果然是。如果不是static 。必须 实例化才能反射。对吗? java 怎么读文件中的一行数据 存到数组中 刚接触java,请教菜单的问题 java 求模运算符 开源 面试的困惑????谁来帮帮我!! 一个关于classpath的问题,解决了就给分! Jdk和Jre的困惑 eclipse里怎么关掉程序? 一个简单的问题? ●●●请问个位在什么情况下需要使用protected来定义函数 ??? 求一道笔试题的解答。。。 关于java Thread的问题
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();
}
}
f.setAccessible(true);
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)
传入class 类型获取静态 类变量