Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java template function

Tags:

java

generics

I have a function that sometimes has to return a 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 it the right approach?
How to use it?

like this (timerHelper is the name of class):

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());
}
like image 357
user72708 Avatar asked Jun 19 '15 13:06

user72708


2 Answers

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.

like image 91
Danikov Avatar answered Sep 19 '22 19:09

Danikov


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

like image 38
OldCurmudgeon Avatar answered Sep 19 '22 19:09

OldCurmudgeon