JavaBean 是一种JAVA语言写成的可重用组件。为写成JavaBean,类必须是具体的和公共的,并且具有无参数的构造器。JavaBean 通过提供符合一致性设计模式的公共方法将内部域暴露成员属性。众所周知,属性名称符合这种模式,其他Java 类可以通过自身机制发现和操作这些JavaBean 属性。
简单的来说JavaBean是有get set方法的特殊的java类,比如
package com.itheima.shipin.javaBean;
public class Student {
String name="heima";
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;
}
}
上面创建了一个student类里面有姓名name,年龄age两种属性并且有相应的get和set方法给这两个属性读取和输出相应的值,并且其中我们默认给name取值为heima。以下对这个JavaBean做个简单的内行操作。
代码如下
package com.itheima.shipin.javaBean;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
public class introspectorTest {
public static void main(String[] args) throws Exception {
Student student = new Student();
String propertyName = "name";
PropertyDescriptor pd = new PropertyDescriptor(propertyName,
student.getClass()); //属性描述
Method metodGetName = pd.getReadMethod();
Object retVal = metodGetName.invoke(student);
System.out.println(retVal);
}
}
运行结果
heima
对以上代码中的
PropertyDescriptor pd = new PropertyDescriptor(propertyName,
student.getClass()); //属性描述
Method metodGetName = pd.getReadMethod();
进行重构
package com.itheima.shipin.javaBean;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class introspectorTest {
public static void main(String[] args) throws Exception {
Student student = new Student();
String propertyName = "name";
Object retVal = getPropertyName(student, propertyName);
System.out.println(retVal);
}
private static Object getPropertyName(Student student, String propertyName)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
PropertyDescriptor pd = new PropertyDescriptor(propertyName,
student.getClass()); //属性描述
Method metodGetName = pd.getReadMethod();
Object retVal = metodGetName.invoke(student);
return retVal;
}
}