I have often come across this requirement across multiple projects, where we need to write a method, which can potentially return object of any class, and still you would not like to do a typecasting. Something like this:
MyClass myClass = getDynamicClass(MyClass.class);
Instead of :
MyClass myClass = (MyClass) getDynamicClass(MyClass.class);
Common example of such use case is where you would do some lookup of a dynamic service (as in OSGi) and return the object found. However, with Java 5 and above this is easy. So, if your earlier code was:
protected Object getDynamicClass(Class interfaceClass) {
Object obj = null;
// code to create / lookup the dynamic object
return obj;
}
This code can be converted as follows:
protected <ReturnType> ReturnType getDynamicClass(Class<ReturnType> interfaceClass) {
Object obj = null;
// code to create / lookup the dynamic object
if (interfaceClass.isInstance(obj)) {
return interfaceClass.cast(obj);
}
return null;
}
This is very obvious code, but thought that sharing this would be useful. Enjoy!