《黑马程序员》基础加强---JavaBean

来源:互联网 发布:只有我知拍摄花絮 编辑:程序博客网 时间:2024/05/28 01:34

------- android培训、java培训、期待与您交流! ----------

什么事JavaBean:

JavaBean是一种特殊的类,他的方法命名有一种特殊的规则。


规则:


1.命名

每个JavaBean都有get/set方法, 比如:

一个person类里面有age,SEX俩个私有变量。

那么他就得提供getAge()/setAge()     getSEX()/setSEX()  这些方法。

解释:如果get/set方法后面跟的字符串第二个字母是小写那么就将该字符串第一个字母变成小写,否则就保持原有, 这样得到的字符串就是变量的名字


2.内省


同过PropertyDescriptor类得到一个属性描述符,然后在得到set/get方法,调用。下面是实例:



IOPOb...


package com.test;import java.beans.IntrospectionException;import java.beans.PropertyDescriptor;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class IntroSpectorDemo {/** * @param args * @throws IntrospectionException  * @throws InvocationTargetException  * @throws IllegalArgumentException  * @throws IllegalAccessException  */public static void main(String[] args) throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {// TODO Auto-generated method stubIOPob iopOb = new IOPob();PropertyDescriptor pd = new PropertyDescriptor("x", IOPob.class);Method getM = pd.getReadMethod();Method setM = pd.getWriteMethod();setM.invoke(iopOb, 10);Integer tmpI = (Integer)getM.invoke(iopOb,null);int x = tmpI.intValue();System.out.print(x);}}

调用上面的getX,setX.

package com.test;import java.beans.IntrospectionException;import java.beans.PropertyDescriptor;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class IntroSpectorDemo {/** * @param args * @throws IntrospectionException  * @throws InvocationTargetException  * @throws IllegalArgumentException  * @throws IllegalAccessException  */public static void main(String[] args) throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {// TODO Auto-generated method stubIOPob iopOb = new IOPob();PropertyDescriptor pd = new PropertyDescriptor("x", IOPob.class);Method getM = pd.getReadMethod();Method setM = pd.getWriteMethod();setM.invoke(iopOb, 10);Integer tmpI = (Integer)getM.invoke(iopOb,null);int x = tmpI.intValue();System.out.print(x);}}

小结:相当于就是反射的简略版了。


0 0