package Day01_Demo.Test05;/*
@create 2020--12--21--11:27
*/
import org.apache.commons.beanutils.BeanUtils;
import org.junit.Test;
import java.lang.reflect.InvocationTargetException;
/**
* BeanUtilsDemo是一个工具类,包含以下两个,
* beanUtils:用于封装数据
* ConverUtils:用于处理数据
*
* 常用的方法:
* setProperty(Object obj,String name,String value):设置属性值,如果找不到指定的属性,不抛异常
* getProperty(Object obj,String name):获取到属性值,如果找不到指定的属性值,抛异常
*/
public class BeanUtilsDemo {
//常规的 - 向User对象中封装数据
//@Test
/*public void test1() {
User user = new User();
user.setUid("u001");
user.setUsername("张三");
System.out.println(user);
}*/
//使用beanUtils工具进行封装
@Test
public void test2() {
//通过工具类使用
User user = new User();
//封装前的配置文件
try {
BeanUtils.setProperty(user, "uid", "u002");
BeanUtils.setProperty(user, "username", "张三丰");
BeanUtils.setProperty(user, "password", "123456");
BeanUtils.setProperty(user, "age", "150");
System.out.println(user);
//获取值
String userName = BeanUtils.getProperty(user, "username");
System.out.println(userName);
//如果找不到key会报错
/* String userName1 = BeanUtils.getProperty(user, "username1");
System.out.println(userName1);//java.lang.NoSuchMethodException: Unknown property 'username1' on class 'class Day01_Demo.Test04.User'*/
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}