Avoid reflection like the plague.
Unfortunately, Java's syntax for this is verbose. (A recent JDK7 proposal would make it much more consise.)
interface ToString {
String toString(T obj);
}
public static Map stringIndexOf(
Iterable things,
ToString toString
) {
Map map = new HashMap();
for (T thing : things) {
map.put(toString.toString(thing), thing);
}
return map;
}
Currently call as:
Map map = stringIndexOf(
things,
new ToString() { public String toString(Thing thing) {
return thing.getSomething();
}
);
In JDK7, it may be something like:
Map map = stringIndexOf(
things,
{ thing -> thing.getSomething(); }
);
(Might need a yield in there.)