CodeSOD: Reflect on Your Mistakes

This post was originally published on this site

The Daily WTF

While Java didn’t invent putting a toString method in the base class of every object, it certainly made it mainstream. The nice thing about the method is that it allows you to turn any object into a string, though it’s up to the implementor to decide what a good string representation is. But what if you want to ensure that the object you’re handed is really and truly a string, not just something you can convert to a string?

teknopaul‘s co-worker found their own solution:

private boolean isString(Object o){ String cl = o.getClass().getName(); if (cl.equalsIgnoreCase(“java.lang.String”)) return true; return false; }

Here, we use reflection to get the class name of an object, and if that class name is java.lang.String, then well- this must be a string!

The beauty of this method is that we lose any compile-time type-safety (which, to be fair, is a thing we risk any

To read the full article click on the 'post' link at the top.