Here's a Java generic pattern:
public <T> T getResultData(Class<T> resultClass, other_args) {
...
return resultClass.cast(T-thing);
}
A typical call looks like:
DoubleBuffer buffer;
buffer = thing.getResultData(DoubleBuffer.class, args);
I've never been able to figure out how to use this pattern cleanly when the desired return type is, itself, generic. To be 'concrete', what if a function like this wants to return Map<String,String>
? Since you can't get a class object for a generic, of course, the only option would be to pass Map.class
, and then you need a cast and an @SuppressWarning
after all.
One ends up with a call like:
Map<String, String> returnedMap;
returnedMap = thing.getResultData(Map.class, some_other_args);
Now one is back to needing casts and suppressing a warning.
I suppose that one could take something from the java.lang.reflect.Type
family instead of the Class
, but those aren't especially easy to concoct. That looks like:
class Dummy {
Map<String, String> field;
}
...
Type typeObject = Dummy.class.getField("field").getGenericType();
Given this, the called function could extract the base type and use that for casting or newInstance-ing, but the dummy field business sure looks ugly.
Note that functions like this are not always calling newInstance
. Obviously, if they do, they don't need to call resultClass.cast
.