An unusual Java construct

I now break the longstanding tradition of not posting code on this blog. I just wanted to share what I believe to be a somewhat unusual pattern in Java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public IMethod findMethod(String name, String[] types) {
		outer:
		for (IMethod m: m_methods)
		{
			if (m.getName().equals(name))
			{
				int i = 0;
				for (IType t: m.getArgList().getTypes())
				{
					if (! t.getName().equals(types[i]))
					{
						continue outer;
					}
					i++;
				}
				return m;
			}
		}
		return null;
	}

On line 2, there’s a label outer: which identifies a location in the code. Normally this feature is used with keywords like the hotly debated goto in C. Java has goto as a keyword, but doesn’t support the feature. However, you can still use the labels with statements like continue above (line 12), which in this case starts a new iteration of the outer loop rather than the inner one.

I can’t remember ever having had to use this feature of any C-like language before (perhaps once) so it was intriguing when it popped up. It’s possible that a neater implementation of this would put the inner loop in a matchesSignature method in the IMethod interface instead.

Comments 2