
本教程操作环境:windows7系统、java10版,DELL G3电脑。
1、说明
(1)反射获取Java类的所有字段,包括所有父类中的字段。 类自身的字段可直接通过方法;
(2)反射可以对字段进行读写,用setX和getX方法对字段进行读写,不过要注意读写前后的类型是否匹配,不然会报异常。
2、实例
privatestaticinta=1;
publicstaticvoidmain(String[]args)throwsNoSuchFieldException,IllegalAccessException{
Classc=Main.class;
Fieldfield=c.getDeclaredField("a");
intb=field.getInt(Main.class);
System.out.println(b);
field.setInt(Main.class,2);
System.out.println(a);
field.setFloat(Main.class,(float)1.1);//报异常
}原文来自:https://www.py.cn © 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
















































暂无评论内容