Defensive copy of Calendar

前端 未结 7 1391
面向向阳花
面向向阳花 2021-01-04 00:38

Been trying to find the best way to implement a method that makes a defensive copy of a Calendar object.

eg:

public void setDate(Calendar date) {
            


        
7条回答
  •  孤城傲影
    2021-01-04 01:03

    This is impossible to guarantee!

    Thread Safety: Cannot be ensured unless you know about the safety scheme implemented by the party from where you got the reference. That party could have given you a new reference in which case you can simply use the reference as is. That party could have published their safety scheme with respect to that Calendar reference, in which case you can follow the same scheme (won't be possible sometimes) to check for non-null references, type and then copy defensively by using getInstance(). Without knowing these, it is impossible to ensure thread safety, I think.

    Defensive Copying of Calendar: cloning isn't an option if you don't trust the place from where you got the reference from! Calendar does not support any constructor that takes an existing Calender object and creates a new one!

    In short, there is no way to solve your issue. JodaTime is the best way forward.

提交回复
热议问题