Java template function

I suspect you're being too clever trying to use generics here. Because you don't have polymorphism on return types doesn't mean you should resort to generics to try and achieve that effect.

You can implement this simply as two methods: public static Date convertToDateForServer(DateTime toSave) {...} and public static DateTime convertToDateTimeForServer(DateTime toSave) {...}. The calling code seems to know what it wants, so it can simply call the method needed. If there really is a complex commonality to both methods, make a private method that both can call internally.


If Java 8 is available you could always implement an Either using the new Optional class.


This is one of the tricky areas of Generics. The only way to get this to work would be to take a Class argument, so the method knows what type of object to create. It can't know at the moment, because of Type Erasure.

Alternatively (much simpler) is to always return DateTime and do away with generics here.

The client will always know what it wants, and if the client wants a Date, it can create one from the DateTime far more easily than what you are trying to do.

Example:

Client 1 wants a DateTime:

DateTime result = service.convertTimeForServer(dt);

Client 2 wants a Date:

Date result = service.convertTimeForServer(dt).toDate();

Tags:

Java

Generics