Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Friday, June 8, 2007

From iterator-loop to foreach-loop with one regex.

Probably the most important feature we've worked on this release was to add Java 5.0 support to EMF. We've learned a lot during the process and actually had some fun trying to make sense out of Generics and Annotations. Of course there were also some very annoying tasks, such as converting Java 1.4 "Iterator loops" into the new "foreach loop" style. For example, this snippet

for (Iterator i = Collections.singleton(new Integer(1)).iterator(); i.hasNext();)
{
Integer integer = (Integer)i.next();
System.out.println(integer);
}

should look like this after the modifications
for (Integer integer : Collections.singleton(new Integer(1)))
{
System.out.println(integer);
}

Unfortunately Eclipse's "Source->Clean..." magic action doesn't do a good job here since it doesn't keep the names and types of the "each" variable. At least back in December, I would end up with Object object : instead of Integer integer : for the example above.

Either to boost my productivity or just to exercise the right to be lazy ;-), I've come up with a regular expression that does the conversion for me. It works flawless with Eclipse's Find dialog (ctrl+f):



Here's a clipboard friendly version:
Find:
(for\s*\(\s*)Iterator\s*\w*\s*=(.*)\.iterator\(\).*;\s*(\)\s*\{\s*)(.*)\s*=.*next\(\);\s*

Replace with:
$1$4:$2$3