【JAVA后端学习之路】JAVA BeanUtils回顾

BeanUtils

  • 通过内省(Introspector)实现,通过读取对象属性值来创建对象。

  • 读取类型均可统一为String类型,因为属性为基本类型时,BeanUtils会自动帮忙转换类型,如下代码示例:

    public class Demo3  {
        public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
    
            String id = "110";
            String name="嘉诚";
            String salary = "1000000";
            Emp p = new Emp();
            BeanUtils.setProperty(p,"id",id);
            BeanUtils.setProperty(p,"name",name);
            BeanUtils.setProperty(p,"salary",salary);
            //Emp p = new Emp(110, "fj", 30000);
            System.out.println(p);
        }
    }
    
  • 如代码块中 Emp p = new Emp(); 类中只需有默认构造函数即可,无需创建带有参数的构造函数,属性值通过BeanUtils.setProperty 传入。

  • 由于是基于内省实现的,所以要求所创建实例所属类

  • 若设置的属性值为其他的 ,则必须注册一个 ,如下代码示例:

    String birthday = "1995-8-1";
    //注册类型转换器
    ConvertUtils.register(new Converter() {
        @Override
        public Object convert(Class type, Object value) {
            Date date = null;
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
                date = dateFormat.parse((String)value);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return date;
        }
    }, Date.class);
    
  • 上述代码旨在将String类型的格式为"yyyy-MM-dd" 的属性值转换为Date引用类型的属性值。

发布了28 篇原创文章 · 获赞 16 · 访问量 3199

猜你喜欢

转载自blog.csdn.net/Newbie_J/article/details/88792101