java-基础-BeanUtils

反射:

public class Demo1 {

public static void main(String[] args) throws Exception {
Person p = (Person) getInstance();
System.out.println(p);
}

//根据配置文件的内容生产对象的对象并且要把对象的属性值封装到对象中。
public static Object getInstance() throws Exception{
BufferedReader bufferedReader = new BufferedReader(new FileReader("obj.txt"));
String className =  bufferedReader.readLine(); //读取配置文件获取到完整的类名。
Class clazz = Class.forName(className);
//通过class对象获取到无参的构造方法
Constructor constructor = clazz.getConstructor(null);
//创建对象
Object o  = constructor.newInstance(null);
//读取属性值
String line = null;
while((line = bufferedReader.readLine())!=null){
String[] datas = line.split("=");
//通过属性名获取到对应的Field对象。
Field field = clazz.getDeclaredField(datas[0]);
if(field.getType()==int.class){
field.set(o, Integer.parseInt(datas[1]));
}else{
field.set(o, datas[1]);
}
}
return o;
}

}

内省:

/*
内省--->一个变态的反射.
内省主要解决 的问题: 把对象的属性数据封装 到对象中。
 */
public class Demo2 {
@Test
public void getAllProperty() throws IntrospectionException{
//Introspector 内省类
BeanInfo beanInfo = Introspector.getBeanInfo(Person.class);
//通过BeanInfo获取所有的属性描述其
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); //获取一个类中的所有属性描述器
for(PropertyDescriptor p : descriptors){
System.out.println(p.getReadMethod()); //get方法
}
}

@Test
public  void testProperty() throws Exception{
Person p = new Person();
//属性描述器
PropertyDescriptor descriptor = new PropertyDescriptor("id", Person.class);
//获取属性对应的get或者是set方法设置或者获取属性了。
Method  m = descriptor.getWriteMethod();  //获取属性的set方法。
//执行该方法设置属性值
m.invoke(p,110);
Method readMethod = descriptor.getReadMethod(); //是获取属性的get方法
System.out.println(readMethod.invoke(p, null));
}

}


BeanUtils:

导包commons-logging.jar 、 commons-beanutils-1.8.0.jar

/*
  BeanUtils主要解决 的问题: 把对象的属性数据封装 到对象中。
 
 BeanUtils的好处:
  1. BeanUtils设置属性值的时候,如果属性是基本数据 类型,BeanUtils会自动帮我转换数据类型。
  2. BeanUtils设置属性值的时候底层也是依赖于get或者Set方法设置以及获取属性值的。
  3. BeanUtils设置属性值,如果设置的属性是其他的引用 类型数据,那么这时候必须要注册一个类型转换器。
 */
public class Demo3 {
public static void main(String[] args) throws Exception {
//从文件中读取到的数据都是字符串的数据,或者是表单提交的数据获取到的时候也是字符串的数据。
String id ="110";
String name="陈其";
String salary = "1000.0";
String birthday = "2013-12-10";
//注册一个类型转换器
ConvertUtils.register(new Converter() {
@Override
public Object convert(Class type, Object value) { //导入源码 type : 目前所遇到的数据类型。  value :目前参数的值。
Date date = null;
try{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
date = dateFormat.parse((String)value);
}catch(Exception e){
e.printStackTrace();
}
return date;
}
}, Date.class);
Emp  e = new Emp();
BeanUtils.setProperty(e, "id", id);
BeanUtils.setProperty(e, "name",name);
BeanUtils.setProperty(e, "salary",salary);
BeanUtils.setProperty(e, "birthday",birthday);
System.out.println(e);
}
}

猜你喜欢

转载自blog.csdn.net/qq_41875147/article/details/79641679