kaiyu
2021-09-30 eba6f1988c6a7e37e619a27e493b17c244979070
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.moral.util;
 
import java.lang.reflect.Field;
 
/**
 * @ClassName ClassUtils
 * @Description TODO
 * @Author 陈凯裕
 * @Date 2021/9/29 11:11
 * @Version TODO
 **/
public class ClassUtils {
 
    /**
     * @Description: 获取对象的属性值
     * @Param: [obj, propertyName]
     * @return: java.lang.Object
     * @Author: 陈凯裕
     * @Date: 2021/9/29
     */
    public static Object getPropertyValue(Object obj, String propertyName) {
        Class<?> Clazz = obj.getClass();
        Field field;
        if ((field = getField(Clazz, propertyName)) == null)
            return null;
        field.setAccessible(true);
        try {
            Object o = field.get(obj);
            return o;
        } catch (IllegalAccessException e) {
            return null;
        }
    }
 
    private static Field getField(Class<?> clazz, String propertyName) {
        if (clazz == null)
            return null;
        try {
            return clazz.getDeclaredField(propertyName);
        } catch (NoSuchFieldException e) {
            return getField(clazz.getSuperclass(), propertyName);
        }
    }
 
}