------- android培训、java培训、期待与您交流! ----------
JavaBean:为一种特殊的类,类中大多为私有字段,并通过固定的名称,也就是set、get方法来操作信息。
IntroSpector(内省):为了更好的操作对象的属性而出现,有利于操作对象的属性,减少代码的书写。
内省访问JavaBean代码的方法有两种:
1、通过PropertyDescriptor来操作。
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
public class Demo1
{
public static void main(String[] args) throws Exception
{
Student stu=new Student("zhangsan",22);
String PropertyName="name";
PropertyDescriptor pd=new PropertyDescriptor(PropertyName,Student.class);
Method getMethod=pd.getReadMethod();
Method setMethod=pd.getWriteMethod();
Object name=getMethod.invoke(stu);
System.out.println(name);
setMethod.invoke(stu,"lisi");
System.out.println(getMethod.invoke(stu));
}
}
class Student{
private String name;
private int age;
Student(String name,int age){
this.name=name;
this.age=age;
}
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;
}
}
2、通过IntroSpector中的getBeanInfo方法获取BeanInfo,再通过BeanInfo获取PropertyDescriptors,最后通过PropertyDescriptor获取信息。
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
public class Demo1
{
public static void main(String[] args) throws Exception
{
Student stu=new Student("zhangsan",22);
String PropertyName="name";
BeanInfo beaninfo = Introspector.getBeanInfo(Student.class);
PropertyDescriptor[] pds = beaninfo.getPropertyDescriptors();
for(PropertyDescriptor pd:pds){
if(pd.getName().equals(PropertyName)){
System.out.println(pd.getReadMethod().invoke(stu));
break;
}
}
}
}
class Student{
private String name;
private int age;
Student(String name,int age){
this.name=name;
this.age=age;
}
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;
}
}
通过PropertyDescriptor获取信息的方法:
getName() 获得属性的名字。
getPropertyType() 获得属性的class对象;
getReadMethod() 获得用于读取属性值的方法;
getWriteMethod() 获得用于写入属性值的方法;
JavaBean与内省访问技术详解
本文深入探讨了JavaBean的概念以及内省技术在操作JavaBean属性中的应用,包括使用PropertyDescriptor和IntroSpector实现属性的读取和修改。
723

被折叠的 条评论
为什么被折叠?



