問(wèn)題描述
我正在嘗試制作一個(gè)對(duì)象的深層副本,包括一個(gè) GregorianCalendar
實(shí)例.我總是對(duì)使用 clone()
持謹(jǐn)慎態(tài)度,而且這里似乎沒(méi)有被覆蓋,所以我只是逐個(gè)字段地進(jìn)行復(fù)制.理想情況下,會(huì)有一個(gè)復(fù)制構(gòu)造函數(shù),我可以像這樣使用它:
I'm trying to make a deep copy of an object, including a GregorianCalendar
instance. I'm always wary of using clone()
and it doesn't seem to have been overridden here, so I'm just doing the copy field by field. Ideally, there'd be a copy constructor, which I could use like so:
GregorianCalendar newCalendar = new GregorianCalendar(oldCalendar);
不幸的是,我在 API 中找不到任何此類(lèi)功能,并且一直在試圖找出我需要哪些字段才能獲得準(zhǔn)確的副本.那么,要復(fù)制其中一個(gè)日歷,你會(huì)怎么做呢?我在這里錯(cuò)過(guò)了一些簡(jiǎn)單的快捷方式嗎?
Unfortunately I can't find any such functionality in the API and am stuck trying to figure out which fields I need to get an exact copy. So, to make a copy of one of these calendars, how would you do it? Am I missing some simple shortcut here?
推薦答案
java.util.Calendar
已經(jīng)覆蓋了正在工作的 clone()
,所以使用它.此外,Calendar
沒(méi)有很深的數(shù)據(jù)層次——它的數(shù)據(jù)主要是 int
s.
java.util.Calendar
has overridden clone()
which is working, so use it. Furthermore, Calendar
doesn't have a deep data hierarchy — its data are mainly int
s.
要擴(kuò)展答案,您可以調(diào)用 SerializationUtils.clone(...)
(來(lái)自 Apache commons-lang)在任何進(jìn)行深拷貝的對(duì)象上,如果整個(gè)數(shù)據(jù)層次結(jié)構(gòu)實(shí)現(xiàn) Serializable
.
To extend the answer, you can call SerializationUtils.clone(…)
(from Apache commons-lang) on any object which makes a deep copy, if the whole data hierarchy implements Serializable
.
這篇關(guān)于克隆 GregorianCalendar 的最快方法是什么?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!