Generics in Java are particularly interesting. I pretty much get the idea of generics at a class-level, especially because I was first introduced to this concept via templates in C++ a long time back.
However I'm not sure how many know of or are comfortable with generic methods in Java. Most of the time we don't even notice this (eg: in generic methods available via core library classes such as Collections). This is because in most cases, Java's type inference hides it away from the callers.
But when overloading of generic methods comes into play, the "ugliness" of generic methods cannot be avoided by the callers. Here's example code that demonstrates my point.
class SomeClass { public String toString() { return "I'm SomeClass instance!"; } } class SomeSubClass extends SomeClass { public String toString() { return "I'm SomeSubClass instance!"; } } public class ClassWithGenericMethod { public String stringify(SomeClass obj) { return "SomeClass instance, try getting around me! Muuaaaahaaa haaa!"; } public <T> String stringify(T obj) { return obj.toString(); } public static void main(String[] args) { ClassWithGenericMethod classWithGenericMethod = new ClassWithGenericMethod(); System.out.println(classWithGenericMethod.stringify(new SomeClass())); System.out.println(classWithGenericMethod.stringify(new SomeSubClass())); System.out.println(classWithGenericMethod.<SomeClass>stringify(new SomeClass())); System.out.println(classWithGenericMethod.<SomeSubClass>stringify(new SomeSubClass())); } }
Output:
SomeClass instance, try getting around me! Muuaaaahaaa haaa! SomeClass instance, try getting around me! Muuaaaahaaa haaa! I'm SomeClass instance! I'm SomeSubClass instance!
As you can see, if you are not aware of the unwieldy syntax of calling a generic method (obj.<ClassName>genericMethod()), you cannot get around the evil all-consuming stringify(SomeClass obj) method.