Wednesday, July 20, 2016

A Cute Trick with Generics to Avoid Unwanted Casts

I ran into a cute trick while coding a unit test on a Spring application the other day that I'd like to share.

Consider these lines of Java code.
The first line requires a cast.  the reason is that the method returns an Object.  While the cast isn't the most labor intensive construct, but it makes code less clear and is inconvenient to developers.

Note that the second line does *not* require the cast making it much more convenient for developers. the secret is that Spring's ReflectionTestUtils uses generics. take a peak at how invokeMethod is defined.


In effect, Java infers the type of the value returned by the definition of the variable it is assigned to. In this case, it's a String.

This is convenient for developers in that there's less to type, but also more easily read.

You should not that the developer is required to know what type of value is returned. The following statement will generate a ClassCastException.


This might seem like a disadvantage to using generics in this way. I don't think so. In either case, the developer needs to understand the data type that will actually be returned.


Just thought I'd pass this tid bit along. I'll certainly think more about using generics in this way in APIs I write.

No comments:

Post a Comment