反射应用(三)
1. 紧接着我们学习了反射应用如何去反射类中的变量
2. 输出类中变量要通过getDeclaredFields()方法调用
3. 代码如下:
4. public void test()throws Exception{
5. //1、加载类
6. Class cls =Class.forName("cn.csdn.reflect.Student");
7. //2、创建类的实例
8. Student entity = (Student)cls.newInstance();
9. //3、解析属性
10. Field fds[] = cls.getDeclaredFields(); //字段
11. System.out.println("=========="+fds.length);
12. for(Field fd:fds){
13. fd.setAccessible(true);
14. System.out.println(fd.getName());
15. }
16. }
17. 当变量为私有的要通过getDeclaredField()方法调用,在强制执行。
18. 代码如下:
19. @Test
20. public void test2()throws Exception{
21. //1、加载类
22. Class cls =Class.forName("cn.csdn.reflect.Student");
23. //2、创建类的实例
24. Student entity = (Student)cls.newInstance();
25. Field fd = cls.getDeclaredField("name"); //获取字段的值 private
26. fd.setAccessible(true); //强制执行
27. fd.set(entity, "redarmy"); //set 赋值(entity,"")
28. //System.out.println(entity.getName());
29. String value = (String)fd.get(entity); //get(entity)
30. System.out.println(value);
31. }