Fun With Generics: Return Anything

If you want to return anything in Java, you usually use Object – with Java 5 and autoboxing, this even allows to return primitive types.

But with Generics, you can do better: You can return whatever the caller wants.

How? Like so:

     public <T> T get() {
        @SuppressWarnings( "unchecked" )
        T result = (T) ...calculate the result...;
            
        return result;
     }

Use cases: Calling unknown methods or reading field values with the Reflection API. Instead of cluttering your code with casts, just write (where ReflectionUtils.invokeMethod() uses the trick above):

     Map<String, List<Map<String, String>> map = Maps.newHashMap();
     Set<List<Map<String, String>> entries = ReflectionUtils.invokeMethod( map, "entrySet" );

Cool, eh?

Unfortunately, Sun’s javac isn’t smart enough to determine a common upper bound between int and Object. So if you need to return int, you still need a cast:

     Map<String, List<Map<String, String>> map = Maps.newHashMap();
     int size = ReflectionUtils.invokeMethod( map, "size" );

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: