本帖最后由 我是楠楠 于 2018-6-11 16:11 编辑
【郑州校区】Java内省机制
内省概述内省(Introspector)是Java语言对JavaBean类的属性,事件和方法的默认处理方式 例如: 类User中有属性name,那么必定有getName,setName方法,内省就是通过这两个方法来获取或者设置name属性的值。 JavaBean就是一个满足了特定格式的Java类 内省类库示例代码 1.存在类User [AppleScript] 纯文本查看 复制代码 public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
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;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
} 2.通过内省获取User类的所有属性:
[AppleScript] 纯文本查看 复制代码 public class StudentTest {
public static void main(String[] args) throws IntrospectionException {
// 通过Introspector.getBeanInfo方法获取指定JavaBean类的BeanInfo信息
BeanInfo beanInfo = Introspector.getBeanInfo(Student.class);
// 通过BeanInfo的getPropertyDescriptors方法获取被操作的JavaBean类的所有属性
// 注意,该属性是通过get/set方法推断出来的属性
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
// 遍历所有的属性
for (PropertyDescriptor pd : pds) {
// 获取属性的名字
String propName = pd.getName();
System.out.println(propName);
// 获取属性的类型
Class propType = pd.getPropertyType();
System.out.println(propType);
// 获取属性对应的get方法
Method getMethod = pd.getWriteMethod();
System.out.println(getMethod);
// 获取属性对应的set方法
Method setMethod = pd.getReadMethod();
System.out.println(setMethod);
}
}
} 3.创建一个User对象,通过内省,设置该对象的name属性的值为"张三丰"
[AppleScript] 纯文本查看 复制代码 // 创建一个没有任何参数的Student对象s
Student s = new Student();
// 通过PropertyDescriptor类的构造方法,直接获取Student类的name属性
PropertyDescriptor pd = new PropertyDescriptor("name",Student.class);
// 获取name属性对应的set方法
Method setMethod = pd.getWriteMethod();
// 调用set方法给上边创建的s对象的name属性赋值
setMethod.invoke(s, "张三丰");
// 输出s
System.out.println(s); 4.输出结果为: Student [name=张三丰, age=0] 应用场景在很多JavaWeb框架设计的时候,会使用到内省机制. 如: Web开发框架Struts中的FormBean就是通过内省机制来将表单中的数据映射到类的属性上. BeanUtils框架的底层也是通过内省来操作JavaBean对象的. BeanUtilsBeanUtils是一个由Apache软件基金组织编写的,专门用来操作JavaBean对象的一个工具. 主要解决的问题是:可以把对象的属性数据封装到对象中。 它的底层,就是通过内省来实现的.
[AppleScript] 纯文本查看 复制代码 // 向Map集合中封装数据 -- 模拟在javaWeb中,使用request.getParameterMap() 获取的参数数据;
Map<String, Object> map = new HashMap<String, Object>() ;
map.put("name", "张三丰") ;
map.put("age", 200) ;
// 创建一个Student对象
Student s = new Student();
// 通过BeanUtils的populate方法,可以把Map集合中的数据封装到Student中
// 该方法的底层就是通过内省来实现的
BeanUtils.populate(s, map);
扩展内省机制是通过反射来实现的 传智播客·黑马程序员郑州校区地址 河南省郑州市高新区长椿路11号大学科技园(西区)东门8号楼三层 联系电话0371-56061160 / 61/62 来校路线地铁一号线梧桐街站A口出
|