javabean

304 阅读2分钟

简介

javabean是一种协议,是一种基于反射的应用,最开始主要应用于图形组件,方便应用程序调用,后来在其他场合也进行了应用。要求:

  1. 属性vaviable,采用setVariable/getVariable函数访问,boolean的get可以用is
  2. 具有无参构造
  3. 没有成员变量只有get/set时,基于javabean的函数也会认为是变量的。所有javabean是依靠方法的应用,而不管真实的变量

javabean的成员变量:

  1. 成员变量是通过method提取出来的
  2. 索引变量:数据。可以提取整个数据或者进行索引
  3. 捆绑变量:具有addPropertyChangeListener(ropertyChangeListener listener) and removePropertyChangeListener(ropertyChangeListener listener)相关函数的对象。当捆绑的变量发生变化的时候,会通知listener事件。
  4. 限制变量,当限制变量的发生变化的时候,会征求listener的意见,如果有反对,就不执行变量的变化相关变量具有的函数为:addVetoableChangeListener(VetoableChangeListener listener)与 removeVetoableChangeListener(VetoableChangeListener listener)

方法

bean中标的公共对象,不是属性就是方法。

事件

是通过方法得到的,具有下面两个方法

  1. public void addListener(Listener a)
  2. public void removeListener(Listener a)
    The listener type must be a descendant of java.util.EventListener.

beaninfo

bean类对象是通过beaninfo被应用程序调用的,Beaninfo是对bean的分析,形成相关属性、事件。

相关应用

se中有集成javabean的类,比较底层

org.apache.commons.beanutils是appache提供的开源工具,进行方便的操作,他的操作相对简单。

下面的函数通过apache的package对bean object进行操作:

  1. 生成类,并实例化
  2. 设置变量,输出变量
  3. 遍历decriptor
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.Set;

public class JavaBeanClass {


    public static void main(String[] args) throws NoSuchMethodException {
        System.out.println("javaBeans");

        Class<?>  class1=null;
        try {
            class1=Class.forName("Person");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Object  object1=null;
        try {
            object1=class1.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }


        try {
            BeanUtils.setProperty(object1, "name", "zhao");
            BeanUtils.setProperty(object1, "age", "12");
            System.out.println(BeanUtils.getProperty(object1, "name"));
            System.out.println(BeanUtils.getProperty(object1, "age"));

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


        Map<String,String> map1=null;
        try {
            map1=BeanUtils.describe(object1);
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }


        Set<String> set= map1.keySet();
        for(String  str1:set){
            System.out.println(str1+"  :  "+map1.get(str1));
        }


        System.out.println("over");
    }


}