-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntrospectionTest.java
More file actions
71 lines (57 loc) · 1.95 KB
/
IntrospectionTest.java
File metadata and controls
71 lines (57 loc) · 1.95 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
package Chapter5;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/*
* java内省Introspection:java JDK中提供一套方法访问JavaBean的get,set方法
* */
public class IntrospectionTest {
public static void main(String[] args) {
try {
Class userClass=Class.forName("Chapter5.User");
User user=(User) userClass.newInstance();
BeanInfo beanInfo=Introspector.getBeanInfo(userClass);
//得到有getset方法的属性列表
PropertyDescriptor[] pros= beanInfo.getPropertyDescriptors();
for(PropertyDescriptor pro:pros){
System.out.println("--属性"+pro.getName());
if(pro.getName().equals("name")){
//得到写方法
System.out.println("执行name的写方法");
Method setMethod= pro.getWriteMethod();
setMethod.invoke(user, "张三");
}else if(pro.getName().equals("number")){
//得到写方法
Method setMethod= pro.getWriteMethod();
setMethod.invoke(user, 1);
}
if(pro.getName().equals("name")||pro.getName().equals("number")){
//得到读方法
Method getMethod=pro.getReadMethod();
System.out.println("get方法:"+getMethod.invoke(user));
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IntrospectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}