您的位置:首页 > 编程语言 > Java开发

JAVA内省(Introspector)

2015-08-02 23:10 411 查看
什么是Java内省:内省是Java语言对Bean类属性、事件的一种缺省处理方法。

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

[java]
view plaincopy





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;

}

[java]
view plaincopy





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));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: