Monday, April 18, 2011

Making the return type of method as generic

Sometimes we may expect different return type for same function.
Consider the following method:

public static final <X> X myGenericMethod(String property)

The method returns a type of whatever you expect it to be (<X> is defined in the method and is absolutely unbounded).

Calling the method :

In this case, the compiler can guess:

Set<String> s = MyClass.myGenericMethod("Some property");

But if it can't, you must type:
MyClass.<String>myGenericMethod("Some Property");

However note that this is very, very dangerous as no provision is made that the return type actually matches the returned value.
The only advantage this has is that you don't have to cast the return value of such generic lookup methods that can return any type.
Use such constructs with care, because you loose pretty much all type-safety and gain only that you don't have to write an explicit cast at each call to get().
And yes: this pretty much is black magic that blows up at runtime and breaks the entire idea of what generics should achieve.

Also if we don't use generic parameter of method, but rather than class the above method becomes:
class MyClass<T>

    public static final X myGenericMethod(String property)


And now use parametric style only on class object, rather than function.
MyClass<T>.myGenericMethod("Some property");

This facility allows you to create methods in a subclass that return an object whose type is a subtype of that returned by the method it overrides.

No comments:

Post a Comment