Java template function

自闭症网瘾萝莉.ら 提交于 2020-01-14 08:05:54

问题


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());
    }

回答1:


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.




回答2:


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




回答3:


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();


来源:https://stackoverflow.com/questions/30939425/java-template-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!