一、什么是JavaBean?
JavaBean是一种特殊的java类,主要用于传递数据信息,这种java类中的方法主要用于访问私有的字段,且方法名符合某种命名规范 (有get和set方法) 。
二、成员变量设置规则:
去掉set和get后为属性名称,如果去掉后的第二个字母是小写,则把第一个字母变成小写;如果第二个字母是大的,就保持原样。如:
Gettime --> time
GetTime --> Time
getCPU --> CPU
如Person类的JavaBean规范:
class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
三、JavaBean的用处及好处呢?
(1)如果要在两个模块之间传递多个信息,可以将这些信息封装到一个JavaBean中,这种JavaBean的实例对象通常称之为值对象(Value Object,简称VO)。这些信息在类中用私有字段来存储,如果读取或者设置这些字段的值,则需要通过一些相应的方法来访问。简单来说就是JavaBean提供了一个规则,通过这个规则,可以访问别人私有的字段。
总之,一个类被当做javaBean使用时,JavaBean的属性是根据方法名推断出来的,他根本看不到java类内部的成员变量。
(2)JDK中提供了对JavaBean进行操作的一些API,这套API就称为内省。如果你自己去通过getX方法来访问私有的x,这么做就有一定难度,而通过内省这套API操作比普通类的方式更方便。
四、怎么用JavaBean?
(1) 采用遍历BeanInfo的所有属性方式来查找和设置某个ReflectPoint对象的x属性。在程序中把一个类当做JavaBean来看,就是调用IntorSpector.getBeanInfo方法,得到的BeanInfo对象封装了这个类当JavaBean看的结果信息。
package cn.itcast;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
public class Java_31_JavaBean {
public static void main(String[] args) throws Exception {
ReflectPoint pt1 = new ReflectPoint(3, 3);
System.out.println(getProperty(pt1, "x"));
}
private static Object getProperty(Object pt1, String propertyName) throws Exception {
//把一个Java当做JavaBean来看,结果为BeanInfo(Bean的信息)
BeanInfo beanInfo = Introspector.getBeanInfo(pt1.getClass());
//只能得到所有的属性,用迭代取出传递进来的属性
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
Object retVal = null;
for(PropertyDescriptor pd : pds) {
if(pd.getName().equals(propertyName)) {
Method methodGetX = pd.getReadMethod();
retVal = methodGetX.invoke(pt1);
break;
}
}
return retVal;
}
}
package cn.itcast;
public class ReflectPoint {
private int x;
public int y;
public ReflectPoint(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;
}
}
/*注意:声明bean为public class 必须是public。即ReflectPoint权限必须为public,否则会出现如下异常,
Exception in thread "main" java.lang.NoSuchMethodException: Property 'x' has no getter method in class 'class cn.itcast.ReflectPoint'*/
我们发现这个方法只能得到所有的属性,用迭代取出传递进来的属性,有点麻烦,那么有没有简单的方法呢?那就是使用BeanUtils工具。
(2) 因为BeanUtils是开源提供的,所以使用之前要先导包,还要导入第三方包。
BeanUtils工具包提供了getProperty(),setProperty()静态方法。
package cn.itcast;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
public class Java_32_JavaBean_BeanUtils {
public static void main(String[] args) throws Exception {
ReflectPoint pt1 = new ReflectPoint(3, 3);
//BeanUtils是以字符串的方式对据JavaBean进行操作
BeanUtils.setProperty(pt1, "x", "7");//设置为字符串“7”;
System.out.println(BeanUtils.getProperty(pt1, "x"));
//PropertyUtils是以本身的类型对据JavaBean进行操作
PropertyUtils.setProperty(pt1, "x", 9);
System.out.println(PropertyUtils.getProperty(pt1, "x"));
}
}