复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31public class UserFanShe { public static void main(String[] args) { User user = new User(); user.setAge(20); user.setName("张三"); TestFanShe(user); // 反射后的值 System.out.println("反射后的name:"+user.getName() + ";反射后的age:" + user.getAge()); } public static <T> void TestFanShe(final T t) { Field[] fields = t.getClass().getDeclaredFields(); Field field = null; for(int i =0; i < fields.length ; i ++) { try { field = fields[i]; field.setAccessible(true); // 开启访问权限 String val = String.valueOf(field.get(t)); // 拿出属性值 System.out.println("属性名称:" + field.getName() +" ; 值为: " + val); System.out.println(field.getType()); if(field.getType() == String.class) { field.set(t,"李四"); // 给属性重新赋值 } } catch (Exception e) { e.printStackTrace(); } } } }
最后
以上就是野性八宝粥最近收集整理的关于通过反射获得对象的属性、属性值、属性类型的全部内容,更多相关通过反射获得对象内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复