-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Expand file tree
/
Copy pathPrivateHelper.java
More file actions
78 lines (65 loc) · 2.05 KB
/
PrivateHelper.java
File metadata and controls
78 lines (65 loc) · 2.05 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.springboot.cloud.common.test;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class PrivateHelper {
private PrivateHelper() {
}
/**
* 创建实例
*
* @return
*/
public static PrivateHelper getInstance() {
return SingletPrivateHelper.sInstance;
}
/**
* 静态内部类单例模式
* 单例初使化
*/
private static class SingletPrivateHelper {
private static final PrivateHelper sInstance = new PrivateHelper();
}
/**
* @param instance 实例对象
* @param fieldName 成员变量名
* @param value 值
*/
public void setPrivateField(Object instance, String fieldName, Object value) {
Field signingKeyField = ReflectionUtils.findField(instance.getClass(), fieldName);
ReflectionUtils.makeAccessible(signingKeyField);
ReflectionUtils.setField(signingKeyField, instance, value);
}
/**
* 寻找对象有参方法
*
* @param instance 实例对象
* @param methodName 方法名
* @param parameterTypes 方法参数类型
* @return
*/
public Method findMethod(Object instance, String methodName, Class<?>... parameterTypes) {
return ReflectionUtils.findMethod(instance.getClass(), methodName, parameterTypes);
}
/**
* 寻找对象无参方法
*
* @param instance 实例对象
* @param methodName 方法名
* @return
*/
public Method findMethod(Object instance, String methodName) {
return ReflectionUtils.findMethod(instance.getClass(), methodName);
}
/**
* 将么有方法设置为可访问,并调用该方法
*
* @param instance 实例对象
* @param method 方法对象
* @param args
*/
public Object invokePrivateMethod(Object instance, Method method, Object... args) {
ReflectionUtils.makeAccessible(method);
return ReflectionUtils.invokeMethod(method, instance, args);
}
}