根據類名與字段名稱取值(可用於循環取實體所有值非常好用)


/**

* 根據字段名稱取值

* 

* @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;

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM