用反射写的取属性值和设置属性值得方法
生活随笔
收集整理的這篇文章主要介紹了
用反射写的取属性值和设置属性值得方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 package com.lovo.util;
2
3 import java.lang.reflect.Constructor;
4 import java.lang.reflect.Field;
5
6 public class MyUtil {
7 private MyUtil(){
8 throw new AssertionError();
9 }
10 /**
11 * 通過反射獲取對象的字段值
12 * @param target 目標對象
13 * @param fieldName 字段名稱
14 * @return 字段的值或null
15 */
16 public static Object getValue(Object target,String fieldName) {
17 Object value = null;
18 //用"."分割例如:"car.engine"表示target對象的(Car類型)car屬性的(Engine)engine屬性值
19 String[] strs = fieldName.split("\\.");
20 for (int i = 0; i < strs.length; i++) {
21 if (target != null) {
22 try {
23 Class<?> clazz = target.getClass();//得到target對象類的類類型對象(描述target對象類的類對象)
24 Field f = clazz.getDeclaredField(strs[i]);//得到屬性
25 f.setAccessible(true);
26 if (i == strs.length - 1) {
27 value = f.get(target);//得到屬性值29 } else {
30 target = f.get(target);//修改target
31 }
32 } catch (Exception e) {
33 throw new RuntimeException(e);
34 }
35 }
36 }
37 return value;
38 }
39 /**
40 * 設置屬性值
41 * @param target 目標對象
42 * @param fieldName 屬性
43 * @param value 值
44 */
45 public static void setValue(Object target,String fieldName,Object value) {
46 Class<?> clazz = target.getClass();
47 String[] trs = fieldName.split("\\.");
48 for (int i = 0; i < trs.length - 1; i++) {
49 try {
50 Field f = clazz.getDeclaredField(trs[i]);
51 f.setAccessible(true);
52 // Object tempTarget = target;
53 // target = f.get(target);
54 if (f.get(target) == null) {
55 String type = f.getGenericType().toString();//得到值為null的屬性的類型的字符串
56 String[] typeSplits = type.split(" ");
57 clazz = Class.forName(typeSplits[1]);//得到值為null的屬性的類型的類類型對象
58 Constructor<?> con = clazz.getDeclaredConstructor();//得到屬性的無參構造器
59 con.setAccessible(true); //有可能是private的所以設置可以訪問
60 f.set(target, con.newInstance());//給null屬性賦值
61 }
62 target = f.get(target);
63 clazz = target.getClass();
64
65 } catch (Exception e) {
66 e.printStackTrace();
67 throw new RuntimeException();
68 }
69 }
70 try {
71 Field f = clazz.getDeclaredField(trs[trs.length - 1]);
72 f.setAccessible(true);
73 f.set(target, value);
74
75 } catch (Exception e) {
76 throw new RuntimeException();
77 }
78 }
79 }
?
轉載于:https://www.cnblogs.com/f644135318/p/4148559.html
總結
以上是生活随笔為你收集整理的用反射写的取属性值和设置属性值得方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ElasticSearch学习笔记-02
- 下一篇: JAVA笔记11__File类/File