高薪笔记----内省机制(IntorSpector)----javabean

来源:互联网 发布:淘宝如何添加店铺活动 编辑:程序博客网 时间:2024/06/05 08:46

Javabean的出现时为了通过提供符合一致性的设计模式的公共方法将内部域暴露成员属性。将类必须是具体的和公共的,并且具有无参数的构造器。

class Person{

private int x;

public void setAge(int age){

this.x= age;

}

public int getAge(){

void x;

}

简单来说哦,javabean就是将类中的成员封装成统一模式get/set的访问格式,对外暴露内部成员(age),其他Java 类可以通过自身机制发现和操作这些JavaBean 属性

备注:x是普通类的成员,而如果将Person当做是一个javabean来使用,对外暴露出来的javabean的属性就是age

如果一个类中出现了get,set方法,那么我们就可以说这是一个javabean类,可以当做javabean来使用。去掉get/set就是javabean的属性,而且应该将Age的首字母(如果首字母是大小,且第二个字母是小写)变成小写。如果首字母是小写,那么javabean属性就是后边的单词。

我们可以通过内省的方式来操作javabean属性。

package cn.itcast.person.demo;

import java.beans.BeanInfo;

import java.beans.IntrospectionException;

import java.beans.Introspector;

import java.beans.PropertyDescriptor;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

public class PersonDemo {

/**

 * @param args

 * @throws IntrospectionException 

 * @throws InvocationTargetException 

 * @throws IllegalAccessException 

 * @throws IllegalArgumentException 

 */

public static void main(String[] args) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {

// TODO Auto-generated method stub

Person p = new Person(2,4);

String properType = "x";

Object retVal = getMethod(p, properType);

System.out.println(retVal);

Object value = 8;

setMethod(p, properType, value);

System.out.println(p.getX());

}

private static void setMethod(Person p, String properType, Object value)

throws IntrospectionException, IllegalAccessException,

InvocationTargetException {

PropertyDescriptor pd = new PropertyDescriptor(properType, p.getClass());

Method methodSetX = pd.getWriteMethod();

methodSetX.invoke(p, value);

}

private static Object getMethod(Person p, String properType)

throws IntrospectionException, IllegalAccessException,

InvocationTargetException {

/*PropertyDescriptor pd = new PropertyDescriptor(properType, p.getClass());

Method methodGetX =pd.getReadMethod();

Object retVal =methodGetX.invoke(p);*/

Object retVal = null;

BeanInfo beanInfo =  Introspector.getBeanInfo(p.getClass());

PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();

for (PropertyDescriptor pd : pds) {

if(pd.getName().equals(properType)){

Method methodGetX = pd.getReadMethod();

retVal = methodGetX.invoke(p);

break;

}

}

return retVal;

}

}

0 0
原创粉丝点击