Fun With Generics: Return Anything

13. January, 2012

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" );

Wrapping Reflection with FEST-Reflect

6. February, 2008

Tired of handling all those pesky exceptions in Java Reflection? I’ve patched commons-beanutils to convert them into RuntimeExceptions but the patch was rejected because it’s a breaking change. Now, you can try FEST Reflection.

FEST Reflection has a nice and small API with an emphasis on making it easy to produce readable code.

Links: Found on DZone Javalobby