javabean 嵌套属性赋值



import java.beans.PropertyDescriptor;
import org.apache.commons.beanutils.PropertyUtils;

/**
* 需beanutils jar包
* 属性格式嵌套用"."相隔
*/
public class Test {
public static void main(String[] args) throws Exception {
Class<?> c = A.class;
Object instance = c.newInstance();
String name ="name";
String value ="aname";
setBeanProperty(instance, name, value);
name = "b.name";
value="bname";
setBeanProperty(instance, name, value);
A a = (A) instance;
System.out.println(a.getName()+":"+a.getB().getName());
}

/**
* populate property
* @param o 实例对象
* @param name 被赋值属性字符描述 格式:a.b.c.....
* @param value 原始值
* @throws Exception
*/
private static void setBeanProperty(Object o,String name,String value) throws Exception{
String[] propDiscribe = name.split("\\.");
if(propDiscribe.length==1){//simple
PropertyUtils.setProperty(o, name, value);
}else{//nested property
if(initNestedProperties(o,name)){
PropertyUtils.setNestedProperty(o, name, value);
};
}
}

/**
* 初始化嵌套属性前面的对象
* 如a.b.name 先检测对象a的b属性是否为null,若是构造空对象
* @param obj
* @param fieldDescribe
* @return
*/
private static boolean initNestedProperties(Object obj, String fieldDescribe){
try{
String[] fieldNames = fieldDescribe.split("\\.");
if (fieldNames.length > 1) {
StringBuffer nestedProperty = new StringBuffer();
for (int i = 0; i < fieldNames.length - 1; i++) {
String fn = fieldNames[i];
if (i != 0) {
nestedProperty.append(".");
}
nestedProperty.append(fn);
Object value = PropertyUtils.getProperty(obj, nestedProperty.toString());
if (value == null) {
PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(obj, nestedProperty.toString());
Class<?> propertyType = propertyDescriptor.getPropertyType();
Object newInstance = propertyType.newInstance();
PropertyUtils.setProperty(obj, nestedProperty.toString(), newInstance);
}
}
}
}catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}




public class A {
private String name;
private B b;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public B getB() {
return b;
}
public void setB(B b) {
this.b = b;
}
}



public class B {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值