根据类名与字段名称取值(可用于循环取实体所有值非常好用)

/**

* 根据字段名称取值

* 

* @param obj 类名

* @param fieldName 属性名

* @return

*/

public static Object getClassValue(Object obj, String fieldName) {

if (obj == null) {

return null;

}

try {

Class beanClass = obj.getClass();

Method[] ms = beanClass.getMethods();

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

// 非get方法不取

if (!ms[i].getName().startsWith("get")) {

continue;

}

Object objValue = null;

try {

objValue = ms[i].invoke(obj, new Object[] {});

} catch (Exception e) {

// logger.info("反射取值出错:" + e.toString());

continue;

}

if (objValue == null) {

continue;

}

if (ms[i].getName().toUpperCase().equals(fieldName.toUpperCase())

|| ms[i].getName().substring(3).toUpperCase().equals(fieldName.toUpperCase())) {

return objValue;

} else if (fieldName.toUpperCase().equals("SID") && (ms[i].getName().toUpperCase().equals("ID")

|| ms[i].getName().substring(3).toUpperCase().equals("ID"))) {

return objValue;

}

}

} catch (Exception e) {

// logger.info("取方法出错!" + e.toString());

}

return null;

}

posted @ 2018-03-18 16:16  马艳泽  阅读(1992)  评论(0编辑  收藏  举报