StringBuffer为什么不能克隆?
StringBuffer buffer = new StringBuffer();
StringBuffer buffer2 = buffer.clone();
要什么样的对象才能进行克隆? 

解决方案 »

  1.   

    你得判断这个类有没有实现Cloneable,实现了的才可以克隆的 判断的方法用instanceof来判断,比如:
    Test t=new Test();
    Test tmp;
    if(t instanceof Cloneable)
    {
           tmp=t.clone();
    }
      

  2.   

    因为clone()方法是protected类型的,所以,下面代码:
    package zhao;public class testClone  implements Cloneable { /**
     * @param args
     */
    public static void main(String[] args) {
    StringBuffer sb = new StringBuffer();
    StringBuffer buffer2 = (StringBuffer)sb.clone();  // 因为clone()方法是protected类型的,所以不能在另一个类中使用StringBuffer的clone方法,没发实现 }
    }
    你要克隆对象得做 2件事情
    第一:要实现Cloneable接口(红色部分)
    第二:重写(覆盖)clone方法(红色部分)代码如下:
    package zhao;public class TestClone  implements Cloneable { /**
     * @param args
     */
    public static void main(String[] args) {
    TestClone t = new TestClone(); 
    TestClone t1 = (TestClone)t.clone(); }
    public Object clone() {
    Object o = null;
    try {
    o = super.clone();
    } catch (CloneNotSupportedException e) {
    e.printStackTrace();
    }
    return o;
    }}
      

  3.   

    不好意思,上面代码设置颜色的地方出错了... 是多余的了
    package zhao;public class TestClone  implements Cloneable { /**
     * @param args
     */
    public static void main(String[] args) {
    TestClone t = new TestClone(); 
    TestClone t1 = (TestClone)t.clone(); }
    public Object clone() {
    Object o = null;
    try {
    o = super.clone();
    } catch (CloneNotSupportedException e) {
    e.printStackTrace();
    }
    return o;
    }}
      

  4.   

    恩,大家都很早啊。。要实现Cloneable接口,,,,,,
    因为有些类已经实现好了,所以不用自己写代码