循环遍历Java类中的所有字段
我有一个Java类,它有很多Fields
。
我想循环遍历allhe字段并为null的那些做一些事情。
例如,如果我的class级是:
public class ClassWithStuff { public int inty; public stringy; public Stuff; //many more fields }
在另一个位置,我会创建一个ClassWithStuff
对象,我想通过该类中的所有字段。 有点像这样:
for (int i = 0; i < ClassWithStuff.getFields().size(); i++) { //do stuff with each one }
有什么办法可以让我实现这个目标吗?
在[Class]上使用getDeclaredFields
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 )
是的,有了反思。
使用Class
对象使用getFields()
方法访问Field
对象。
Field[] fields = ClassWithStuff.class.getFields();
然后循环遍历字段。 这是有效的,因为您声明的所有字段都是public
。 如果不是,则使用getDeclaredFields()
,它访问在类上直接声明的所有Fields
, public
或不public
。
寻找的东西叫reflection 。 通过reflection,您可以查看自己的类或其他类,以查看它的组成。 Java内置了reflectionfunction,因此您可以立即使用它。 然后你可以做的事情 –
for(Field f : ClasWithStuff.getFields()){ System.out.println(f.getName());//or do other stuff with it }
您也可以使用它来获取方法,构造函数等,以执行类似和更酷的操作。
使用库durian和Stream
Java 8+解决方案。
实用方法FieldsAndGetters.fields(Object obj)
返回给定对象的所有公共字段及其值的Stream。
这将找到ClassWithStuff
的字段,因为它们都是公共的。
让我们看看如何使用它(稍微修改一下) ClassWithStuff
:
public static class BaseStuff { public DayOfWeek dayOfWeek = DayOfWeek.MONDAY; } public static class ClassWithStuff extends BaseStuff { public int inty = 1; public String stringy = "string"; public Object Stuff = null; }
示例 – 打印每个字段的名称和值:
public static void main(String[] args) throws Exception { ClassWithStuff cws = new ClassWithStuff(); FieldsAndGetters.fields(cws) .map(field -> field.getKey().getName() + " = " + field.getValue()) .forEach(System.out::println); }
输出:
inty = 1 stringy = string Stuff = null dayOfWeek = MONDAY
正如ouptut所示,甚至考虑了inheritance的公共领域。