vendredi 19 juin 2015

Java template function

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
        }
}

It is the right approach?
How I have 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());

How I use this function instead?

static public <T extends Object> T current_Moment(){
        return convertTimeForServer(new DateTime());
    }

Aucun commentaire:

Enregistrer un commentaire