/
ReflectionUtils.java
40 lines (37 loc) · 1.14 KB
/
ReflectionUtils.java
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
package com.github.zagum.switchicon;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectionUtils {
public static boolean setValue(Object object, String fieldName, Object fieldValue) {
Class<?> clazz = object.getClass();
while (clazz != null) {
try {
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, fieldValue);
return true;
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
return false;
}
public static boolean callMethod(Object object, String methodName, Class<?>... params) {
Class<?> clazz = object.getClass();
while (clazz != null) {
try {
Method method = clazz.getDeclaredMethod(methodName, params);
method.setAccessible(true);
method.invoke(object, null);
return true;
} catch (NoSuchMethodException e) {
clazz = clazz.getSuperclass();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
return false;
}
}