JavaBean

来源:互联网 发布:淘宝买家贷款操作流程 编辑:程序博客网 时间:2024/06/07 03:34
一、定义:
     把一个拥有对属性进行set和get方法的类,我们就可以称之为JavaBean。实际上JavaBean就是一个java类,在这个java类中就默认形成了一种规则——对属性进行设置和获得。而反之将说java类就是一个JavaBean,这种说法是错误的,因为一个java类中不一定有对属性的设置和获得的方法(也就是不一定有set和get方法)。
二、从JavaBean中就引出了一个内省的概念
     内省:把一类中需要进行设置和获得的属性访问权限设置为private(私有的)让外部的使用者看不见摸不着,而通过public(共有的)set和get方法来对其属性的值来进行设置和获得,而内部的操作具体是怎样的?外界使用的人不用不知道,这就称为内省。
三、使用内省解释JavaBean中setProperty()和getProperty()方法的实现原理。实际上也是用反射的那一套做法
 
package itcast.Test5;import java.beans.PropertyDescriptor;import java.lang.reflect.Method;/*5、写一个方法,public void setProperty(Object obj, String propertyName, Object value){},此方法可将obj对象中名为propertyName的属性的值设置为value。*///这题中用了内省的简单应用,理解到了JavaBean中setProperty()方法和getProperty()方法的实现public class SetPropertyTest {     /**     * @param args     */     public static void main(String[] args) {          // TODO Auto-generated method stub          Point pt1 = new Point(3, 5);          String propertyName = "x";          Object value = 7;                   getProperty(pt1, propertyName);                   setProperty(pt1, propertyName, value);                   System.out.println(pt1.getX());     }     //setProperty()方法的实现     private static void setProperty(Object object, String propertyName, Object value) {          try {               //使用java.beans包中的PropertyDescriptor(属性操作符类)               PropertyDescriptor pd2 = new PropertyDescriptor(propertyName, object.getClass());               //通过反射来得到Point这个javabean的set方法               Method methodSetX = pd2.getWriteMethod();               methodSetX.invoke(object,value);          } catch (Exception e) {               // TODO: handle exception          }     }     //getProperty()方法的实现     private static void getProperty(Object object, String propertyName) {          try {               PropertyDescriptor pd1 = new PropertyDescriptor(propertyName, object.getClass());               Method methodGetX = pd1.getReadMethod();               Object retVal = methodGetX.invoke(object);               System.out.println(retVal);          } catch (Exception e) {               // TODO: handle exception          }     }}class Point {     private int x;     private int y;         public Point(int x, int y) {          super();          this.x = x;          this.y = 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;     }    }

原创粉丝点击