Wednesday

Java Fun: When all you have is a hammer...

I ought to be ashamed, but I was bored and lazy, so I thought I'd test my somewhat dormant Java skills. Can you tell me (without running it) what this code does?

Method[] methods = Foo.class.getMethods();
String source = FileUtils.readFully(new FileReader(
"src/main/java/"
+ Foo.class.getCanonicalName().replaceAll(
"\\.", "/") + ".java"));
PrintStream out = System.out;
for (Method method : methods) {
Matcher matcher = Pattern.compile(
"public (\\S+?) " + method.getName() + "\\((.*?)\\)",
Pattern.DOTALL | Pattern.MULTILINE).matcher(source);
if (matcher.find()) {
String ret = matcher.group(1);
String params = matcher.group(2);
out.printf(" public %s %s(", ret, method.getName());
out.print(params);
out.print(") {\n ");
if (!"void".equals(ret)) {
out.print("return ");
}
out.print("foo.");
out.print(method.getName());
out.print('(');
if (!StringUtils.isEmpty(params)) {
out.print(StringUtils.join(CollectionUtils.collect(
Arrays.asList(params.split(",\\s*")),
new Transformer() {
public Object transform(Object input) {
return ((String) input).split(" ")[1];
}
}), ','));
}
out.println(");\n }\n");
}
}

I'll post the equivalent Groovy (and maybe JavaScript) later. I imagine I can do it in a single statement function. I don't miss Java very much.

No comments: