什么是Java内省:内省是Java语言对Bean类属性、事件的一种缺省处理方法。
Java内省的作用:一般在开发框架时,当需要操作一个JavaBean时,如果一直用反射来操作,显得很麻烦;所以sun公司开发一套API专门来用来操作JavaBean
- package com.javax.iong.javabean0301;
- public class Person {
- private String name;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- private int age;
- }
- package com.javax.iong.javabean0301;
- import java.beans.BeanInfo;
- import java.beans.Introspector;
- import java.beans.PropertyDescriptor;
- import java.lang.reflect.Method;
- import org.junit.Test;
- public class Test1 {
- @Test
- public void tes1() throws Exception {
- Class<?> cl = Class.forName("com.javax.iong.javabean0301.Person");
- // 在bean上进行内省
- BeanInfo beaninfo = Introspector.getBeanInfo(cl, Object.class);
- PropertyDescriptor[] pro = beaninfo.getPropertyDescriptors();
- Person p = new Person();
- System.out.print("Person的属性有:");
- for (PropertyDescriptor pr : pro) {
- System.out.print(pr.getName() + " ");
- }
- System.out.println("");
- for (PropertyDescriptor pr : pro) {
- // 获取beal的set方法
- Method writeme = pr.getWriteMethod();
- if (pr.getName().equals("name")) {
- // 执行方法
- writeme.invoke(p, "xiong");
- }
- if (pr.getName().equals("age")) {
- writeme.invoke(p, 23);
- }
- // 获取beal的get方法
- Method method = pr.getReadMethod();
- System.out.print(method.invoke(p) + " ");
- }
- }
- @Test
- public void test2() throws Exception {
- PropertyDescriptor pro = new PropertyDescriptor("name", Person.class);
- Person preson=new Person();
- Method method=pro.getWriteMethod();
- method.invoke(preson, "xiong");
- System.out.println(pro.getReadMethod().invoke(preson));
- }
- }