A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Zhen_霖 初级黑马   /  2013-1-19 02:07  /  1138 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

最近在学习JavaBean下面是我的一些总结,如果有错的话希望大家指出来
一、定义:
     把一个拥有对属性进行set和get方法的类,我们就可以称之为JavaBean。实际上JavaBean就是一个java类,在这个java类中就默认形成了一种规则——对属性进行设置和获得。而反之将说ava类就是一个JavaBean,这种说法是错误的,因为一个java类中不一定有对属性的设置和获得的方法(也就是不一定有set和get方法)。
二、从JavaBean中就引出了一个内省的概念
     内省:把一类中需要进行设置和获得的属性访问权限设置为private(私有的)让外部的使用者看不见摸不着,而通过public(共有的)set和get方法来对其属性的值来进行设置和获得,而内部的操作具体是怎样的?外界使用的人不用不知道,这就称为内省。
三、使用内省解释JavaBean中setProperty()和setProperty()方法的实现原理。实际上也是用反射的那一套做法
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;
     }
   
}

1 个回复

倒序浏览
值得学习ing!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马