-------
android培训、
java培训、期待与您交流! ----------
由内省引出的JavaBean的讲解
JavaBean 是一种特殊的Java类,主要用于传递数据信息,这种java类中的方法主要用于访问私有的字段,且方法名符合某种命名规则。
如果第二个字母是小写的,则把第一个字母改成小写的
如果第二个字母是大写写的,则把第一个字母也要是大写的
如: setId() 的属性名--> id
setCPU() 的属性名是 --> CPU
下面是一段简单的一个JavaBean类代码:
class Student {
private String name;
private int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = 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中,这种JavaBean的实体对象,通常称之为值对象(Value Object,简称VO),这些信息在类中用私有字段来存储,如果读取或设置这些字段值,则需要通过一些方法来访问。 一个JavaBean类可以不当JavaBean用,而是当成普通类用。JavaBean实际就是一种规范,当一个类满足这个规范,这个类就能被其它特定的类调用.
代码:Student类:
class Student {
private String name;
private int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = 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;
}
}
JavaBeanTest测试类:
package cn.itcast;
import java.beans.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class JavaBeanTest {
public static void main(String[] args) throws Exception {
Student stu1 = new Student("Mike",22);
String propertyName = "name";
PropertyDescriptor pd = new PropertyDescriptor(propertyName, stu1.getClass());
Method methodGetName = pd.getReadMethod();
Object retval = methodGetName.invoke(stu1);
System.out.println(retval);
Method methodSetName = pd.getWriteMethod();
methodSetName.invoke(stu1, "David");
System.out.println(stu1.getName());
}
}
用重构来写
JavaBeanTest 类:
public class JavaBeanTest {
public static void main(String[] args) throws Exception {
Student stu1 = new Student("Mike",22);
String propertyName = "name";
Object retval = getProperty(stu1, propertyName);
System.out.println(retval);
setProperty(stu1, propertyName);
System.out.println(stu1.getName());
}
private static void setProperty(Student stu1, String propertyName)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
PropertyDescriptor pd2 = new PropertyDescriptor(propertyName, stu1.getClass());
Method methodSetName = pd2.getWriteMethod();
methodSetName.invoke(stu1, "David");
}
private static Object getProperty(Student stu1, String propertyName)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
PropertyDescriptor pd = new PropertyDescriptor(propertyName, stu1.getClass());
Method methodGetName = pd.getReadMethod();
Object retval = methodGetName.invoke(stu1);
return retval;
}
}