Java模板功能 [英] Java template function

查看:42
本文介绍了Java模板功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,有时不得不返回Date而不是DateTime(Joda-Time).

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?

像这样(timerHelper是类的名称):

like this (timerHelper is the name of class):

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

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

推荐答案

我怀疑您在这里尝试使用泛型太聪明了.因为您对返回类型没有多态性,但这并不意味着您应该使用泛型来尝试达到这种效果.

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.

您可以简单地通过两种方法来实现此目的:public static Date convertToDateForServer(DateTime toSave) {...}public static DateTime convertToDateTimeForServer(DateTime toSave) {...}.调用代码似乎知道它想要什么,因此可以简单地调用所需的方法.如果这两种方法确实存在复杂的通用性,请创建一个可以在内部调用的私有方法.

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.

这篇关于Java模板功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆