------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------
一、javabean的内省操作:
(1) 首先明白什么是javabean:javabean就是符合特定规则的特殊类。这些方法主要的功能四访问私有成员,私有成员值的获取和设置是通过getX()和setX()来访问的,且X是属性名,若一个java类满足这些书写规则,我们就可以认为是一个javabean。
(2)其次明白什么是内省操作:jdk提供了一些关于对javabean操作的api,这些api对javabean的操作过程,我们就称为是javabean的内省操作。常用的api:Introspector,propertyDescriptor,BeanInfo等类。
二、简单javabean的内省操作实现:
(1)首先建立一个javabean对象,代码如下:
package com.javabeans;
public class ReflectPoint {
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
(2)建立一个IntrospectorTest类,实现对javabean属性值的访问和设置,代码如下:
package com.javabeans;
import java.beans.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.apache.commons.beanutils.*;
public class IntrospectorTest {
public static void main(String[] args) throws Exception {
//简单的javabean内省操作
ReflectPoint rp1=new ReflectPoint(3,4);
String propertyName ="x";
//若是要利用反射机制比较的麻烦 但是javabean给我们提供了一个propertyDescriptor
PropertyDescriptor pd=new PropertyDescriptor(propertyName,rp1.getClass());
//获取对于属性的成员方法 ---getX()
Method method= pd.getReadMethod();
//调用方法
Object i=method.invoke(rp1);
System.out.println(i);
//调用set方法
Method method1=pd.getWriteMethod();
method1.invoke(rp1, 100);
System.out.println(method.invoke(rp1));
System.out.println("*************");
beanInfor(rp1);
System.out.println("*************");
System.out.println(beanUtil());
System.out.println("*************");
}
//个人认为:这就是 beanUtils的内部实现,利用反射,动态获取加载类的属性和方法
//再利用获取的方法操作相应的属性,只是 BeanUtils把这些内部细节封装好了,给外部 提供接口使用
//内省的简单操作
public static void beanInfor(ReflectPoint rp1)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
//存放bean的所有的信息
BeanInfo beanInfo=Introspector.getBeanInfo(ReflectPoint.class);
//获取bean信息中的属性
PropertyDescriptor []pds=beanInfo.getPropertyDescriptors();
for(PropertyDescriptor p:pds){
if(p.getName().equals("x")){
Method method2=p.getReadMethod();
System.out.print(method2.invoke(rp1));
}
}
}
//内省的复杂操作,利用beanutils工具来操作javabean
public static String beanUtil(){
System.out.println("你好");
ReflectPoint rp2=new ReflectPoint(3,6);
try {
BeanUtils.setProperty(rp2, "x", 1);
return BeanUtils.getProperty(rp2, "x");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
(3)javabean的复杂内省操作:就是利用BeanUtils工具类对javabean属性的操作,具体代码如上所述。
三、补充说明(BeanUtils)
BeanUtils是常用的操作javabean的类,我们可以简单的理解为:BeanUtils就是用来对javabean属性值的设置和获取的一个类,理解了这点,我们就很好的掌握了这个类。
------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ---------