public class Student {
//综上,这个类有三个属性
private String name;//字段
private int age;//字段
public String getName() {//属性指的是设置set和读取get字段的方法
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAbc() {//属性名称是abc
return "abc";
}
}
测试类:`package cn.itcast.base.enumou;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.Console;
import javax.xml.ws.handler.MessageContext.Scope;
import org.junit.Test;
public class Demo1 {
//内省是操作属性的(类的getter和setter方法)
//例如getClass() 它的属性是class getAbc 是abc
@Test
public void test1() throws Exception{
//得到Student类中的属性,病封装到BeanInfo中去
BeanInfo bi=Introspector.getBeanInfo(Student.class);
//得到类中的所有属性描述器
PropertyDescriptor[] pds=bi.getPropertyDescriptors();
System.out.println(pds.length);
for(PropertyDescriptor pd:pds) {
System.out.println(pd.getName());
}
}
}
打印结果如下:
4
abc
age
class
name
`
`注意:每个类都有一个默认属性。只要是Object类型,都有getClass()属性``
使用:
@Test
public void test2() throws Exception{
Student student=new Student();
PropertyDescriptor pDescriptor=new PropertyDescriptor("name", Student.class);
Method method1=pDescriptor.getReadMethod();//得到get方法
String string=(String)method1.invoke(student, null);
Method method2=pDescriptor.getWriteMethod();
method2.invoke(student, "高蒙");
}
## 内省框架
BeanUtils是Apache开发的一套快速操作JavaBean getter/setter方法的api,目前比较流行
准备包: commons-beanutils.jar commons-logging.jar
语法:
设置:BeanUtils.setProperty(Object bean,String PropertyName,String PropertyValue);
获取:BeanUtils.getProperty(Object bean,String PropertyName);
`` @Test
public void test3() throws Exception{
Student student=new Student();
//为什么要返回字符串,因为用户所有的输入都是字符串
String string=BeanUtils.getProperty(student,"name");
BeanUtils.setProperty(student,"name","高蒙");
}
****BeanUtils可以进行类型类型转换,但仅限基本类型(例如Date类型就不行)
之前说过,用户输入的都是字符串类型,所以就牵扯一个问题
字符串<--------------->其他类型之间的相互转换
所以需要给BeanUtils注册类型转换器
下面有更简单的实现
改版上述程序(选择已有的日期转换器)