forked from jenkinsci/office-365-connector-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReflectionHelper.java
More file actions
57 lines (49 loc) · 1.84 KB
/
ReflectionHelper.java
File metadata and controls
57 lines (49 loc) · 1.84 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
package jenkins.plugins.office365connector.helpers;
import hudson.util.ReflectionUtils;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.stream.Stream;
public class ReflectionHelper {
public static <T> T invokeMethod(Object target, String methodName, Object... args) {
Method method;
if (args == null || args.length == 0) {
method = ReflectionUtils.findMethod(target.getClass(), methodName);
} else {
Class<?>[] paramTypes = Stream.of(args).map(arg -> {
// mocked classes...
if (arg.getClass().getSimpleName().contains("$Mockito")) {
try {
return Class.forName(StringUtils.substringBefore(arg.getClass().getName(), "$Mockito"));
} catch (Exception ex) {
throw new IllegalStateException(ex);
}
} else {
return arg.getClass();
}
}).toArray(Class<?>[]::new);
method = ReflectionUtils.findMethod(target.getClass(), methodName, paramTypes);
}
if (method == null) {
throw new IllegalStateException("Could not find method " + methodName);
}
ReflectionUtils.makeAccessible(method);
return (T) ReflectionUtils.invokeMethod(method, target, args);
}
public static <T> T getField(Object target, String fieldName) {
Field field = ReflectionUtils.findField(target.getClass(), fieldName);
if (field == null) {
throw new IllegalStateException("Could not find field " + fieldName);
}
ReflectionUtils.makeAccessible(field);
return (T) ReflectionUtils.getField(field, target);
}
public static void setField(Object target, String fieldName, Object value) {
Field field = ReflectionUtils.findField(target.getClass(), fieldName);
if (field == null) {
throw new IllegalStateException("Could not find field " + fieldName);
}
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, target, value);
}
}