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