-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReflectUtils.java
More file actions
40 lines (37 loc) · 1.19 KB
/
Copy pathReflectUtils.java
File metadata and controls
40 lines (37 loc) · 1.19 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
package com.utils;
import java.lang.reflect.Field;
/**
* @author ManhKM on 10/19/2022
* @project Java-Reflection
*/
public class ReflectUtils {
public static boolean set(Object object, String fieldName, Object fieldValue){
Class<?> clazz = object.getClass();
if(clazz != null){
try{
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, fieldValue);
return true;
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
clazz = clazz.getSuperclass();
}
}
return false;
}
public static Object get(Object object, String fieldName){
Class<?> clazz = object.getClass();
if(clazz != null){
try{
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(object);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
clazz = clazz.getSuperclass();
}
}
return null;
}
}