java遍歷類的字段屬性及其字段值


public class ReflectUtil {

 public static void reflect(Object o){
  //獲取參數類
  Class cls = o.getClass();
  //將參數類轉換為對應屬性數量的Field類型數組(即該類有多少個屬性字段 N 轉換后的數組長度即為 N)
  Field[] fields = cls.getDeclaredFields();
  for(int i = 0;i < fields.length; i ++){
   Field f = fields[i];
   f.setAccessible(true);
   try {
    //f.getName()得到對應字段的屬性名,f.get(o)得到對應字段屬性值,f.getGenericType()得到對應字段的類型
    System.out.println("屬性名:"+f.getName()+";屬性值:"+f.get(o)+";字段類型:" + f.getGenericType());
   } catch (IllegalArgumentException | IllegalAccessException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
 public static void main(String[] args) {
  Student s = new Student();
  s.setName("張三");
  s.setAge(12);
  s.setGrade(89);
  reflect(s);
 }
}


免責聲明!

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



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