-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommonUtils.java
More file actions
67 lines (58 loc) · 2.09 KB
/
Copy pathCommonUtils.java
File metadata and controls
67 lines (58 loc) · 2.09 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
package com.utils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
/**
* @author ManhKM on 8/1/2022
* @project Java-Reflection
*/
public class CommonUtils {
// get thông tin Class:
public static void getClassInfo(Class clazz){
System.out.println(String.format("Class: %s", clazz.getName()));
System.out.println(String.format("Package: %s", clazz.getPackage().getName()));
System.out.println(String.format("Modifier public: %s", Modifier.isPublic(clazz.getModifiers())));
}
// get thông tin các trường
public static void getFields(Class clazz){
Field[] fs = clazz.getDeclaredFields();
for (int i = 0; i < fs.length; i++){
System.out.println(fs[i].getType());
System.out.println(" " + fs[i].getName());
}
}
// get thông tin method:
public static void getMethods(Class clazz){
Method[] ms = clazz.getDeclaredMethods();
for (int i = 0; i < ms.length; i++){
System.out.println(ms[i].getName());
Parameter[] ps = ms[i].getParameters();
for (int j = 0; j < ps.length; j++){
System.out.println(" " + ps[j].getParameterizedType());
System.out.println(" " + ps[j].getName());
}
}
}
// tạo mới đối tượng:
public static Object createObject(Class clazz, String[] fields, Object[] values){
try {
Object obj = clazz.newInstance();
for(int i = 0; i < fields.length; i++){
Field field = clazz.getDeclaredField(fields[i]);
field.setAccessible(true);
field.set(obj, values[i]);
}
return obj;
} catch (InstantiationException e) {
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
} catch (NoSuchFieldException e) {
e.printStackTrace();
return null;
}
}
}