javaBean对象toString方法,javabeantostring
javaBean对象toString方法,javabeantostring
package com.baic.core.base.util;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class GetPropertyValue {
public final static String getPropertyValue(Object obj) {
if(obj==null){
return null;
}else{
if (String.class.isInstance(obj)
|| Integer.class.isInstance(obj)
|| Double.class.isInstance(obj)
|| Float.class.isInstance(obj)
|| Long.class.isInstance(obj)
|| Short.class.isInstance(obj)) {
return (String) obj;
} else {
StringBuffer strBuffer = new StringBuffer();
Field[] fields = obj.getClass().getDeclaredFields();
if (fields != null && fields.length > 0) {
for (int i = 0, j = fields.length; i < j; i++) {
strBuffer.append(fields[i].getName() + ":");
Method getMethod = getPropertyDescriptor(obj.getClass(),
fields[i].getName()).getReadMethod();
if (getMethod != null) {
try {
strBuffer.append(String.valueOf(getProperty(obj,fields[i].getName()))
+ "##");
} catch (Exception e) {
strBuffer.append("##");
}
} else {
strBuffer.append("##");
}
}
} else {
return strBuffer.toString();
}
return strBuffer.toString();
}
}
}
/**
* <p>方法描述: [方法功能中文描述]</p>
*
* @param clazz 参数说明
* @param propertyName 参数说明
*
* @return 返回结果的说明
*/
@SuppressWarnings("unchecked")
public static PropertyDescriptor getPropertyDescriptor(Class clazz,
String propertyName) {
StringBuffer sb = new StringBuffer(); //构建一个可变字符串用来构建方法名称
Method setMethod = null;
Method getMethod = null;
PropertyDescriptor pd = null;
try {
Field f = clazz.getDeclaredField(propertyName); //根据字段名来获取字段
if (f != null) {
//构建方法的后缀
String methodEnd = propertyName.substring(0, 1).toUpperCase()
+ propertyName.substring(1);
sb.append("set" + methodEnd); //构建set方法
//构建set 方法
setMethod = clazz.getDeclaredMethod(sb.toString(),
new Class[] { f.getType() });
sb.delete(0, sb.length()); //清空整个可变字符串
sb.append("get" + methodEnd); //构建get方法
//构建get 方法
getMethod = clazz.getDeclaredMethod(sb.toString(),
new Class[] {});
//构建一个属性描述器 把对应属性 propertyName 的 get 和 set 方法保存到属性描述器中
pd = new PropertyDescriptor(propertyName, getMethod, setMethod);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return pd;
}
public static Object getProperty(Object obj, String propertyName) {
PropertyDescriptor pd = getPropertyDescriptor(obj.getClass(), propertyName); //获取 clazz 类型中的 propertyName 的属性描述器
Method getMethod = pd.getReadMethod(); //从属性描述器中获取 get 方法
Object value = null;
try {
value = getMethod.invoke(obj, new Object[]{ }); //调用方法获取方法的返回值
} catch (Exception e) {
e.printStackTrace();
}
return value; //返回值
}
}
相关文章
- 暂无相关文章
用户点评