8

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());
}
HK boy
  • 1,398
  • 11
  • 17
  • 25
user72708
  • 1,235
  • 3
  • 13
  • 20

3 Answers3

7

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.

Danikov
  • 735
  • 3
  • 10
2

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

Community
  • 1
  • 1
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
2

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();
NickJ
  • 9,380
  • 9
  • 51
  • 74