1. package Day01_Demo.Test05;/*
    2. @create 2020--12--21--11:27
    3. */
    4. import org.apache.commons.beanutils.BeanUtils;
    5. import org.junit.Test;
    6. import java.lang.reflect.InvocationTargetException;
    7. /**
    8. * BeanUtilsDemo是一个工具类,包含以下两个,
    9. * beanUtils:用于封装数据
    10. * ConverUtils:用于处理数据
    11. *
    12. * 常用的方法:
    13. * setProperty(Object obj,String name,String value):设置属性值,如果找不到指定的属性,不抛异常
    14. * getProperty(Object obj,String name):获取到属性值,如果找不到指定的属性值,抛异常
    15. */
    16. public class BeanUtilsDemo {
    17. //常规的 - 向User对象中封装数据
    18. //@Test
    19. /*public void test1() {
    20. User user = new User();
    21. user.setUid("u001");
    22. user.setUsername("张三");
    23. System.out.println(user);
    24. }*/
    25. //使用beanUtils工具进行封装
    26. @Test
    27. public void test2() {
    28. //通过工具类使用
    29. User user = new User();
    30. //封装前的配置文件
    31. try {
    32. BeanUtils.setProperty(user, "uid", "u002");
    33. BeanUtils.setProperty(user, "username", "张三丰");
    34. BeanUtils.setProperty(user, "password", "123456");
    35. BeanUtils.setProperty(user, "age", "150");
    36. System.out.println(user);
    37. //获取值
    38. String userName = BeanUtils.getProperty(user, "username");
    39. System.out.println(userName);
    40. //如果找不到key会报错
    41. /* String userName1 = BeanUtils.getProperty(user, "username1");
    42. System.out.println(userName1);//java.lang.NoSuchMethodException: Unknown property 'username1' on class 'class Day01_Demo.Test04.User'*/
    43. } catch (IllegalAccessException e) {
    44. e.printStackTrace();
    45. } catch (InvocationTargetException e) {
    46. e.printStackTrace();
    47. } catch (NoSuchMethodException e) {
    48. e.printStackTrace();
    49. }
    50. }
    51. }