黑马程序员——javabean、内省和BeanUtils

来源:互联网 发布:linux mount 目录 编辑:程序博客网 时间:2024/06/03 15:09

---------------------- ASP.Net+Unity开发.Net培训、期待与您交流! ----------------------

一、Javabean的命名规范


javabean,是一个特殊的类。它不像其他类一样依靠继承某些接口而实现。对于javabean,只要你的Java类书写符合某些规范就可以算是javabean。

下面表格表示属性名与方法名对应关系:

属性名/类型getter 方法setter 方法xcoordinate/Doublepublic Double getXcoordinate()public void setXcoordinate(Double newValue)xCoordinate/Doublepublic Double getxCoordinate()public void setxCoordinate(Double newValue)XCoordinate/Doublepublic Double getXCoordinate()public void setXCoordinate(Double newValue)Xcoordinate/Double不允许不允许student/Booleanpublic Boolean getStudent()public void setStudent(Boolean newValue)student/booleanpublic boolean getStudent()
public boolean isStudent()public void setStudent(boolean newValue)

二、内省(introspector)和BeanUtils

内省作用:提供了一些静态方法,可以获取目标javabean文件的BeanInfo(包含变量、方法、事件)。

机制:内省检查的是目标类的get/set方法,符合Javabean规则就算作一个变量。不需要知道类内部具有哪些变量,可以直接由传入的类Class字解码文件获取全部属性。即使是私有的变量也能获取到。

与内省不同,BeanUtils 相当于依照JavaBean规则书写的一个通过传入(对象、变量名、值),对类的属性进行设置、获取的操作。

参考其API:http://commons.apache.org/proper/commons-beanutils/javadocs/v1.8.3/apidocs/index.html

三、实例(Introsperctor)

import java.beans.BeanInfo;import java.beans.IntrospectionException;import java.beans.Introspector;import java.beans.PropertyDescriptor;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;class Test {public static void main(String[] args) throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {// TODO Auto-generated method stubIntrospectorDemo demo=new IntrospectorDemo();demo.setName("来自猩猩的你");//内省BeanInfo bi=Introspector.getBeanInfo(demo.getClass(),Object.class);//使用这个方法,获取限制条件(Object.class)父类以下的属性信息PropertyDescriptor[] pd=bi.getPropertyDescriptors();Object retval=null;for (PropertyDescriptor propertyDescriptor : pd) {//String name=propertyDescriptor.getName();Method method=propertyDescriptor.getReadMethod();retval=method.invoke(demo);System.out.println(propertyDescriptor.getName());//属性名System.out.println(retval);//属性值}}}//JavaBean对象public class IntrospectorDemo {private String name=null;public String getName() {return name;}public void setName(String name) {this.name = name;}}


上文有注释的地方,添加则输出:name                来自猩猩的你

    否则输出:class     class 包名.IntrosperctorDemo                      name               来自猩猩的你


PS:注意细节,测试半天才看出来了


---------------------- ASP.Net+Unity开发.Net培训、期待与您交流! ----------------------

0 0
原创粉丝点击