Yep. A very valid point. Unfortunately, that's the trade off when using a metadata driven solution (in this case reflection). I was worried about that when I added the isValid() method as a runtime check to return whether the name passed in matched any of the public fields/methods in the class definition, but it's still runtime. My biggest concern is non-string fields and methods. I can get around that as well by checking class and return types.
In my sample program, I actually use it this way:
Code:
StringComparator strcomp = new StringComparator(p1, "getFullName", "method");
if (strcomp.isValid()) {
Collections.sort(testvec, strcomp);
}else{
//do something useful here
} I just had another thought. Since the valid list of field and method names is stored within the Comparator object, I could make those items available so that they could populate a drop down in a GUI or something. That would eliminate typos as a source of error, at least in that type of app.
Thanks for the feedback! This is mostly an exercise in seeing if it could be done, but I might just use it.