JAVA内省(Introspector)

来源:互联网 发布:windows无法识别音响 编辑:程序博客网 时间:2024/06/05 10:51

什么是Java内省:内省是Java语言对Bean类属性、事件的一种缺省处理方法。

Java内省的作用:一般在开发框架时,当需要操作一个JavaBean时,如果一直用反射来操作,显得很麻烦;所以sun公司开发一套API专门来用来操作JavaBean

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. package com.javax.iong.javabean0301;  
  2.   
  3. public class Person {  
  4.       
  5.     private String name;  
  6.     public String getName() {  
  7.         return name;  
  8.     }  
  9.     public void setName(String name) {  
  10.         this.name = name;  
  11.     }  
  12.     public int getAge() {  
  13.         return age;  
  14.     }  
  15.     public void setAge(int age) {  
  16.         this.age = age;  
  17.     }  
  18.     private int age;  
  19.   
  20. }  

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. package com.javax.iong.javabean0301;  
  2.   
  3. import java.beans.BeanInfo;  
  4. import java.beans.Introspector;  
  5. import java.beans.PropertyDescriptor;  
  6. import java.lang.reflect.Method;  
  7.   
  8. import org.junit.Test;  
  9.   
  10. public class Test1 {  
  11.   
  12.     @Test  
  13.     public void tes1() throws Exception {  
  14.         Class<?> cl = Class.forName("com.javax.iong.javabean0301.Person");  
  15.         // 在bean上进行内省  
  16.         BeanInfo beaninfo = Introspector.getBeanInfo(cl, Object.class);  
  17.         PropertyDescriptor[] pro = beaninfo.getPropertyDescriptors();  
  18.         Person p = new Person();  
  19.         System.out.print("Person的属性有:");  
  20.         for (PropertyDescriptor pr : pro) {  
  21.             System.out.print(pr.getName() + " ");  
  22.         }  
  23.         System.out.println("");  
  24.         for (PropertyDescriptor pr : pro) {  
  25.             // 获取beal的set方法  
  26.             Method writeme = pr.getWriteMethod();  
  27.             if (pr.getName().equals("name")) {  
  28.                 // 执行方法  
  29.                 writeme.invoke(p, "xiong");  
  30.             }  
  31.             if (pr.getName().equals("age")) {  
  32.                 writeme.invoke(p, 23);  
  33.             }  
  34.             // 获取beal的get方法  
  35.             Method method = pr.getReadMethod();  
  36.             System.out.print(method.invoke(p) + " ");  
  37.   
  38.         }  
  39.     }  
  40.   
  41.     @Test  
  42.     public void test2() throws Exception {  
  43.         PropertyDescriptor pro = new PropertyDescriptor("name", Person.class);  
  44.         Person preson=new Person();  
  45.         Method  method=pro.getWriteMethod();  
  46.         method.invoke(preson, "xiong");  
  47.         System.out.println(pro.getReadMethod().invoke(preson));  
  48.     }  

0 0
原创粉丝点击