java 獲取對象屬性值與屬性名稱


/**
* 獲取對象屬性,返回一個字符串數組
*
* @param o 對象
* @return String[] 字符串數組
*/
private static String[] getFiledName(Object o)
{
  try
  {
    Field[] fields = o.getClass().getDeclaredFields();
    String[] fieldNames = new String[fields.length];
    for (int i=0; i < fields.length; i++)
    {
    fieldNames[i] = fields[i].getName();
    }
    return fieldNames;
  } catch (SecurityException e)
  {
  e.printStackTrace();
  System.out.println(e.toString());
  }
  return null;
}

/**
* 使用反射根據屬性名稱獲取屬性值
*
* @param fieldName 屬性名稱
* @param o 操作對象
* @return Object 屬性值
*/

private static Object getFieldValueByName(String fieldName, Object o)
{
  try
  {
    String firstLetter = fieldName.substring(0, 1).toUpperCase();
    String getter = "get" + firstLetter + fieldName.substring(1);
    Method method = o.getClass().getMethod(getter, new Class[] {});
    Object value = method.invoke(o, new Object[] {});
    return value;
  } catch (Exception e)
  {
  System.out.println("屬性不存在");
  return null;
  }
}


免責聲明!

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



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