用 Java 扩展日历
我想从 java.util.Calendar 向日历添加更多方法,但在使用 getInstance 方法时遇到问题。
如果我有一个像这样的对象:public class DateObject extends Calendar{ // 这里还有其他方法 }
我这样做 DateObject mon = DateObject.getInstance();
该代码不起作用。即使我将其替换为 Calendar.getInstance(),我也无法将日历转换为我的 DateObject。
如何让我的 DateObject 使用 getInstance()?
I wanted to add more methods to the Calendar from java.util.Calendar, but I'm having trouble using the getInstance method.
If I have an object like:public class DateObject extends Calendar{ // other methods here }
And I do DateObject mon = DateObject.getInstance();
The code does not work. Even if I replace it with Calendar.getInstance(), I can't convert a Calendar to my DateObject.
How do I make my DateObject use getInstance()?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
getInstance()
是Calendar
上的静态方法。您不能覆盖静态方法。您将需要提供您自己的方法。但我会质疑扩展日历的设计。让你的班级包装日历而不是扩展它,几乎肯定会为你提供更好的服务。特别是,更改日历实现将变得非常非常困难。
还要考虑一下,日历 API 在很多方面都非常糟糕,所以让它永久存在将是对小猫的犯罪。
您是否考虑过使用可能已经包含您想要的功能的替代日期/时间/日历库?例如JodaTime。
getInstance()
is a static method onCalendar
. You cannot override static methods. You will need to provide your own method.But I would question the design of extending Calendar. You will almost certainly be better served by having your class wrap a Calendar rather than extend it. In particular, changing your calendar implementation will become very, very difficult.
Consider also, that the Calendar API is very broken in a number of respects, so perpetuating it would be a crime against baby kittens.
Have you considered an alternative date/time/calendar library which might already contain the functionality you want? For example JodaTime.
或者,更好的是,找到像 Joda 这样的库,它可以执行您认为必要的任何附加操作。扩展日历的设计几乎肯定会走向错误的方向。
Or, better yet, finding a library like Joda that will do whatever additional operations you seem to think are necessary. A design that extends Calendar is almost certainly headed in a bad direction.
getInstance() 是静态/类方法。你不能。您的用例是什么?
getInstance() is a static/class method. You can't. What's your use case?
创建 Calendar 的子类并不意味着 Calendar 中现有的静态
getInstance()
方法会神奇地知道添加一个或多个具有如下签名的方法
一种解决方案是向 DateObject 类 ,并实现它根据需要创建 DateObject 实例。
另一种可能性是查看现有的 getInstance() 工厂方法如何工作,并弄清楚如何让它创建一个 DateObject 实例。
另外,请注意那些表明扩展日历不是一个好主意的答案。
Creating a subclass of Calendar doe not mean that the existing static
getInstance()
method in Calendar will magically knowOne solution is to add a method or methods with a signature like:
to the DateObject class, and implement it to create DateObject instances as required.
Another possibility is to look at how the existing
getInstance()
factory method works, and figure out how to get it to create one of your DateObject instances.Also, pay attention to the answers that suggest that extending Calendar is a bad idea.