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

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

问题描述

我有一个包含多个 Fields 的 Java 类.

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
}

在另一个位置,我将创建一个 ClassWithStuff 对象,并且我想查看类中的所有字段.有点像这样:

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]

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(myStuff);
   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天全站免登陆