Java template function

I have a function that sometimes needs to return Date other times a DateTime (Joda-Time).

 static public <T extends Object> T convertTimeForServer(DateTime toSave) { DateTime temp = null; try { temp = toSave.withZone(DateTimeZone.forID(getServerTimeZone())); } catch (Exception e) { } T toReturn = null; if (toReturn.getClass().equals(temp)) { return (T) temp;//Return DATETIME } else { return (T) temp.toDate();//Return DATE } } 

Is this the right approach?
How to use it?

like this (timerHelper is the class name):

  DateTime t = timerHelper.<DateTime>convertTimeForServer(new DateTime()); Date t2 = timerHelper.<Date>convertTimeForServer(new DateTime()); or DateTime t = (DateTime)timerHelper.convertTimeForServer(new DateTime()); Date t2 = (Date)timerHelper.convertTimeForServer(new DateTime()); 

And how to use this function instead?

 static public <T extends Object> T current_Moment(){ return convertTimeForServer(new DateTime()); } 
+7
java generics
source share
3 answers

This is one of the complex areas of Generics. The only way to make this work is to accept the class argument, so the method knows what type of object to create. At the moment, he may not know, due to Type Erasure .

Alternatively (much easier) to always return a DateTime and destroy generics here.

The client will always know what he wants, and if the client wants Date , he can create one of DateTime much easier than what you are trying to do.

Example:

Client 1 wants a DateTime :

 DateTime result = service.convertTimeForServer(dt); 

Client 2 wants Date :

 Date result = service.convertTimeForServer(dt).toDate(); 
+2
source share

I suspect you are too smart trying to use generics here. Since you do not have polymorphism by return type, this does not mean that you should resort to generics in order to try to achieve this 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 just call the required method. If there really is a complex community for both methods, create a private method that can call internally.

+5
source share

If Java 8 is available, you can always implement either using the new Optional .

+2
source share

All Articles