通用的java bean_关于Javabean或者实体的通用转化器

通过Java的反射机制,可以获得当前类中的方法或者当前实体的方法和实体的具体的每个值,这个非常灵活,我暂时领悟到这里。

object是个对象

Field[] fields = object.getClass().getDeclaredFields();    返回一个属性的数组

Method[] methods = object.getClass().getMethods();         方法

下面放出代码:用了递归

public static String tt(Object object){

if(object!=null){

String className = object.getClass().getName();

System.out.println("---:"+className);

if(className.startsWith("java.util.")){

System.out.println("3---:"+className);

List list = (List) object;

for (Object object2 : list) {

tt(object);

}

}else if(!className.startsWith("java")){

System.out.println("2---:"+className);

Field[] fields = object.getClass().getDeclaredFields();

Method[] methods = object.getClass().getMethods();

//得到类所有属性

for (int i = 0; i < fields.length; i++) {

String propertyName = fields[i].getName();

System.out.println("propertyName:"+propertyName);

String propertyGetName = NULL_VALUE;

if (propertyName != null && !NULL_VALUE.equals(propertyName)) {

propertyGetName = GET+propertyName.toLowerCase();

}else {

return null;

}

//获取所有方法

for (int j = 0; j < methods.length; j++) {

String methodName = methods[j].getName();

if (methodName != null && !NULL_VALUE.equals(methodName)) {

methodName = methodName.toLowerCase();

}else {

return null;

}

//执行所有访问器

if (methodName.equals(propertyGetName)) {//....

try {

Object propertyValue = methods[j].invoke(object, null);

System.out.println("propertyValue::"+propertyValue);

tt(propertyValue);

} catch (Exception e) {

System.out.println(" >>> get method exception!");

e.printStackTrace();

}

}

}

}

}

}

return null;

}

Object propertyValue = methods[j].invoke(object, null);    //取值的方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值