java的 内省机制_javaBean的内省机制

clazz) throws Exception{

T newInstance = clazz.newInstance();

BeanInfo beanInfo = Introspector.getBeanInfo(clazz);

PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {

//获取属性名

String name = propertyDescriptor.getName();

//如果map中存在这个属性

if(map.get(name)!=null){

Method writeMethod = propertyDescriptor.getWriteMethod();

writeMethod.invoke(newInstance, map.get(name));

}

}

return newInstance;

}

Student类代码   使用lombok封装的

@Data

@AllArgsConstructor

@NoArgsConstructor

public class Student {

private String name;

private int age;

}

是不是非常方便   ,既然这么方便肯定已经有人帮你做好了

下面介绍下apache 的commons包,需要导入两个jar包commons-beanutils-1.9.3.jar 和 commons-logging-1.2.jar

因为commons-beanutils-1.9.3.jar 依赖于commons-beanutils-1.9.3.jar 和 commons-logging-1.2.jar

资源下载页https://download.csdn.net/download/qq_39205291/10520314

将一个map拷贝到 javaBean

Mapm = new HashMap<>();

m.put("name", "小刚");

m.put("age", 3);

Student s1 = new Student();

System.out.println(s1);

BeanUtils.copyProperties(s1, m);

System.out.println(s1);

将一个javaBean拷贝到另外一个 javaBean

Student s1 = new Student("小王",1);

Student s2 = new Student();

System.out.println(s2);

//第一个参数为目标  第二个为源

BeanUtils.copyProperties(s2,s1);

System.out.println(s2);

当出现null或者""转换为integer或者Long等类型时会出现我们不想要的结果

此时可以自定义注册    指定值为null时的转换规则

ConvertUtils.register(new IntegerConverter(null), null);

String对于Date类型转换则必须指定DateConverter否则会报错(主要因为要指定Date的格式)

Mapm = new HashMap<>();

m.put("name", "小刚");

m.put("age", null);

m.put("date","2018-01-01");

Student s1 = new Student();

DateConverter dateConverter = new DateConverter(null);

dateConverter.setPattern("yyyy-MM-dd");

ConvertUtils.register(dateConverter,Date.class);

BeanUtils.copyProperties(s1, m);

System.out.println(s1);

如果本身是Date类型则无需转换

Mapm = new HashMap<>();

m.put("name", "小刚");

m.put("age", null);

m.put("date",new Date());

Student s1 = new Student();

BeanUtils.copyProperties(s1, m);

System.out.println(s1);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值