Cloneableインターフェース
* Java で、プロトタイプパターン(オブジェクトのクローン)を実装するには、 Cloneableインターフェースを実装すればいい。
API仕様書
https://docs.oracle.com/javase/jp/6/api/java/lang/Cloneable.htmlサンプル
Main.java
import java.util.Date; public class Main { public static void main(String[] args) { Person person1 = new Person(1L, "Mike", "m", new Date(), null); System.out.println("Person1 : " + person1.toString()); Person person2 = new Person(2L, "Tom", "m", new Date(), person1); System.out.println("Person2 : " + person2.toString()); Person clonePerson = (Person) person2.clone(); System.out.println("Clone Person : " + clonePerson.toString()); } }
Person.java
* Cloneable インターフェースを継承import java.util.Date; public class Person implements Cloneable { private long id; private String name; private String sex; private Date updatedate; private Person bestFriend; public Person(long id, String name, String sex, Date updatedate, Person person) { this.id = id; this.name = name; this.sex = sex; this.updatedate = updatedate; this.bestFriend = person; } public long getId() { return this.id; } public void setId(long id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getSex() { return this.sex; } public void setSex(String sex) { this.sex = sex; } public Date getUpdatedate() { return this.updatedate; } public void setUpdatedate(Date updatedate) { this.updatedate = updatedate; } public String toString() { String friend = ""; if (this.bestFriend != null) { friend = this.bestFriend.toString(); } return String.format("id=%s, name=%s, sex=%s, updatedate=%s, best friend=%s", this.id, this.name, this.sex, this.updatedate, friend); } // ★注目★ @Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(e.toString()); } } }
出力結果
Person1 : id=1, name=Mike, sex=m, updatedate=Wed Nov 26 23:18:57 JST 2014, best friend= Person2 : id=2, name=Tom, sex=m, updatedate=Wed Nov 26 23:18:57 JST 2014, best friend=id=1, name=Mike, sex=m, updatedate=Wed Nov 26 23:18:57 JST 2014, best friend= Clone Person : id=2, name=Tom, sex=m, updatedate=Wed Nov 26 23:18:57 JST 2014, best friend=id=1, name=Mike, sex=m, updatedate=Wed Nov 26 23:18:57 JST 2014, best friend=
参考文献
http://www.ne.jp/asahi/hishidama/home/tech/java/clone.htmlhttp://funini.com/kei/java/clone.shtml
http://d.hatena.ne.jp/hageyahhoo/20090803/1249298924
http://www.syboos.jp/java/doc/object-clone.html