有没有办法在 Java 中向 GregorianCalendar 添加方法?
我想创建一个名为“isBetween”的方法,返回一个布尔值,看看 GregorianCalendar 日期是否落在另外两个日期之间。或者,我想只定义 < 的运算符和>为了班级。我对 Java 还很陌生,所以我不确定......我什至可以做其中任何一个吗?如果是这样,怎么办?
I'd like to make a method called "isBetween" returning a boolean, seeing if a GregorianCalendar date falls between two others. Alternatively, I'd like to just define operators of < and > for the class. I'm pretty new to Java, so I'm not sure....can I even do either of those? If so, how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Java 不支持猴子补丁或运算符重载,但您可以随意子类化 GregorianCalendar 并添加您需要的任何方法。
但是,您真的需要一种新方法来执行 cal.after(startCal) && 吗? cal.before(endCal) ?
Java does not support monkeypatching or operator overloading, but feel free to subclass
GregorianCalendar
and add whatever methods you need.But then, do you really need a new method to do
cal.after(startCal) && cal.before(endCal)
?不,您不能向预先存在的类添加方法,也不能在 Java 中进行运算符重载。
作为替代方案,您可以在自己的类中提供静态实用方法。
No, you can't add method to pre-existing classes and you can't do operator overloading either in Java.
As an alternative, you could provide a static utility method in your own class for example.
我建议反对扩展该类 - 您没有添加任何特定于特定类的实例的行为,您正在表达适用于任何
GregorianCalendar
的逻辑(或者可能是任何日历)。正如 Joachim 所说,实用程序类中的静态方法是可行的方法 - 如果 Java 按照 C# 获得扩展方法(我知道 Java 7 中建议使用它们,但我认为它们是目前已发布)您可以在此时修改它们。
哦,无论如何,请使用 Joda Time :)
I would advise against extending the class - you're not adding any behaviour which is specific to instances of a particular class, you're expressing logic which is applicable for any
GregorianCalendar
(or possibly any calendar at all).As Joachim says, a static method in a utility class is the way to go - and if Java ever gains extension methods as per C# (I know they were suggested for Java 7, but I think they're out at the moment) you can modify them at that point.
Oh, and use Joda Time anyway :)
你应该尝试扩展它:
You should try to extend it: