循环Java类中的所有字段 [英] Loop over all fields in a Java class

查看:349
本文介绍了循环Java类中的所有字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有 Fields 的Java类。



lthe字段,并为无效的那些做一些事情。



例如如果我的类是:

  public class ClassWithStuff { 
public int inty;
public stringy;
public Stuff;
//更多字段
}

make a ClassWithStuff 对象,我想去遍历类中的所有字段。类似这样的:

  for(int i = 0; i< ClassWithStuff.getFields()。size(); i ++ ){
//对每一个进行操作
}

c> ]

  ClasWithStuff myStuff = new ClassWithStuff(); 
Field [] fields = myStuff.getClass()。getDeclaredFields();
for(Field f:fields){
Class t = f.getType();
Object v = f.get(o);
if(t == boolean.class& amp; Boolean.FALSE.equals(v))
//找到默认值
else if(t.isPrimitive()&& ((Number)v).doubleValue()== 0)
//找到默认值
else if(!t.isPrimitive()&& v == null)
/ /找到默认值
}

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Class.html


I have a Java class that has a number of Fields.

I would like to Loop over al lthe fields and do something for the one's that are null.

For example if my class is:

public class ClassWithStuff {
    public int inty;
    public stringy;         
    public Stuff;
    //many more fields
}

In another location, I'd make a ClassWithStuff object and I would like to go though all the fields in the class. Kind of like this:

for (int i = 0; i < ClassWithStuff.getFields().size(); i++) {
      //do stuff with each one
}

Is there any way for me to achieve this?

解决方案

Use getDeclaredFields on [Class]

ClasWithStuff myStuff = new ClassWithStuff();
Field[] fields = myStuff.getClass().getDeclaredFields();
for(Field f : fields){
   Class t = f.getType();
   Object v = f.get(o);
   if(t == boolean.class && Boolean.FALSE.equals(v)) 
     // found default value
   else if(t.isPrimitive() && ((Number) v).doubleValue() == 0)
     // found default value
   else if(!t.isPrimitive() && v == null)
     // found default value
}

(http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Class.html)

这篇关于循环Java类中的所有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆