Java内省的使用(续)

来源:互联网 发布:网络彩票什么时候恢复 编辑:程序博客网 时间:2024/06/05 04:05

     刚才说了Apache组织结合很多实际开发中的应用场景开发了一套简单、易用的API操作Bean的属性——BeanUtils,也给大家显出了代码的实现。十分简单,便捷。

     那么接下来就让我们来看看其中的几个框架,以及其中一些转换器的使用。

     Person类:

public class Person {private int age;private String name;private Date birth;public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Date getBirth() {return birth;}public void setBirth(Date birth) {this.birth = birth;}public Person(){}}

   测试类:

public class PersonTest {@Testpublic void test() throws Exception {// 得到class对象Class cls = Class.forName("www.csdn.net.beanutils.Person");// 实例化对象Person bean = (Person) cls.newInstance();/** *  BeanUtils框架 */// 设置值BeanUtils.setProperty(bean, "age", "12");// 12本身是字符串,但是在这里就自动转换了(如果为12s,则输出的是0)// 读取值String s = BeanUtils.getProperty(bean, "age");System.out.println("获取利用BeanUtils框架setProperty()设置的值为:" + s);/** PropertyUtils框架 *  */// 设置值PropertyUtils.setProperty(bean, "name", "Retror");// PropertyUtils框架// 读取值Object value = PropertyUtils.getProperty(bean, "name");System.out.println("获取利用PropertyUtils框架setProperty()设置的值为:" + value);// birth属性// 自定义的转换器ConvertUtils.register(new Converter() {public Object convert(Class arg0, Object arg1) {System.out.println(arg0 + "---" + arg1);//类型----字符串if (arg1 == null) {//判断值是否为空return null;} else {try {SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");return sdf.parse((String) arg1);//parse()方法,从给定字符串的开始解析文本,以生成一个日期。该方法不使用给定字符串的整个文本} catch (ParseException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}return null;}}}, Date.class);//采用内部的转换器完成的转换//ConvertUtils.register(new DateLocaleConverter(), Date.class);// 设置属性/** * 自定义转换器实现 *///实现BeanUtils.setProperty(bean, "birth", "1992年10月10日");//BeanUtils.setProperty(bean, "birth", "1992-10-10");// 读取值String v = BeanUtils.getProperty(bean, "birth");System.out.println(v);}}

 

     效果:


    这里,在测试类中通过两个框架(BeanUtils和PropertyUtils)来实现了设置值和读取值的操作,并且在其中利用自定义的转换器来实现日期的转换。希望大家能从中得到一些帮助。

原创粉丝点击