CodeSOD: Reflect on Your Mistakes
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 time we use generics). But if all the methods which want a string input just, y'know, required a string parameter, this method wouldn't be necessary.
But more than that, this breaks polymorphism. I'm not suggesting that we should go and override the string class, but if you did, that string wouldn't cause this function to return true. The isAssignableFrom function would be more appropriate than using getName, but don't confuse "more appropriate" with "actually appropriate".
[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!