Thursday, June 26, 2008

Java : Implementing the C# foreach

This is a common construct:



for (int i = 0; i < "object".length; i++)
{
}



It's messy and in C# you can easily do this far more elegantly with the "foreach" command.

How do you do this in Java?

Use something like e.g. for Reflection fields:



import java.lang.reflect.Field;

Field[] fields = "object".getClass().getDeclaredFields();

for (Field field : fields)
{
...
field[i].getName();
...
}



Enjoy!

No comments: