Java内省api示例

简单理解:

  内省相当于是反射的一个子集。

  内省专门用来操作Bean的。

关于bean:一个set/get就定义了一个属性(包括从父类继承来的get/set)

 

简易代码示例:

一个bean:Person.java,一个内省Demo:Demo_istpt.java

Person.java:

 1 package com.rt.gwq.introspector;
 2 
 3 public class Person {
 4     
 5     private String name ;
 6     private String password ;
 7     private int age ;
 8     public String getName() {
 9         return name;
10     }
11     public void setName(String name) {
12         this.name = name;
13     }
14     public String getPassword() {
15         return password;
16     }
17     public void setPassword(String password) {
18         this.password = password;
19     }
20     public int getAge() {
21         return age;
22     }
23     public void setAge(int age) {
24         this.age = age;
25     }
26     
27 }

Demo_istpt.java:

 1 package com.rt.gwq.introspector;
 2 
 3 import java.beans.BeanInfo;
 4 import java.beans.IntrospectionException;
 5 import java.beans.Introspector;
 6 import java.beans.PropertyDescriptor;
 7 import java.lang.reflect.Method;
 8 
 9 import org.junit.Test;
10 
11 public class Demo_istpt {
12     
13     /**
14      * 获取所有属性描述器
15      * @throws Exception
16      */
17     @Test
18     public void test1() throws Exception{
19         
20         //获取一个Bean的信息
21         BeanInfo  info = Introspector.getBeanInfo(Person.class);
22         //下面语句只获得Person的属性,不包括从Object继承的属性
23 //        BeanInfo  info = Introspector.getBeanInfo(Person.class,Object.class);
24         //获取bean属性的所有描述器
25         PropertyDescriptor[] pds = info.getPropertyDescriptors();
26         for (PropertyDescriptor pd : pds) {
27             System.out.println(pd.getName());
28         }
29         
30     }
31     
32     /**
33      * 通过内省操作Bean方法
34      * @throws Exception
35      */
36     @Test
37     public void test2() throws Exception{
38         
39         Person p = new Person();
40         
41         PropertyDescriptor pd = new PropertyDescriptor("age", Person.class);
42         //获取写方法,即set方法
43         Method w = pd.getWriteMethod();
44         w.invoke(p, (Integer)18);
45         //获取读方法,get方法
46         Method r = pd.getReadMethod();
47         //输出验证
48         System.out.println("age:"+ r.invoke(p, null));
49         //获取类型
50         System.out.println("age type:"+pd.getPropertyType());
51         
52         
53     }
54 
55 }

 

转载于:https://www.cnblogs.com/WinKinGo/p/5516138.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值