summaryrefslogtreecommitdiff
path: root/src/main/java/com/keuin/ohmyvanillamc/ReflectionUtils.java
blob: a87632e531dc1f29e3676b011ba424d2a2c77f03 (plain)
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
46
47
48
49
50
51
package com.keuin.ohmyvanillamc;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @Author 落叶飞翔的蜗牛 Keuin
 * @Date 2018/3/10
 * @Description 常用反射函数
 */
public final class ReflectionUtils {

    /**
     * 获取私有成员变量的值
     */
    public static Object getPrivateField(Object instance, String filedName) throws NoSuchFieldException, IllegalAccessException {
        Field field = instance.getClass().getDeclaredField(filedName);
        field.setAccessible(true);
        return field.get(instance);
    }

    /**
     * 设置私有成员的值
     */
    public static void setPrivateField(Object instance, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {
        Field field = instance.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(instance, value);
    }

    /**
     * 访问私有方法
     */
    public static Object invokePrivateMethod(Object instance, String methodName, Class[] classes, Object... args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method method = instance.getClass().getDeclaredMethod(methodName, classes);
        method.setAccessible(true);
        return method.invoke(instance, args);
    }

    /**
     * 获取所有成员变量的名字
     *
     * @param o 要获取成员变量的对象实例
     * @return 所有成员变量名字数组
     */
    public static String[] getFieldName(Object o) {
        return Arrays.stream(o.getClass().getDeclaredFields()).map(Field::getName).toArray(String[]::new);
    }
}