[FindBugs分析记录]Class defines clone() but doesn't implement Cloneable

官网解释:

  This class defines a clone() method but the class doesn't implement Cloneable. There are some situations in which this is OK (e.g., you want to control how subclasses can clone themselves), but just make sure that this is what you intended.

 什么代码会引起这个问题呢?先看下面:

class MyTest {

    public MyTest clone(){

        MyTest myTest = new MyTest();

        return myTest;          

    }           

}    

这段代码会引起FindBugs的这个警告,为什么?请看下面解释:

1.根据FindBugs的说明,如果一个类重写clone()函数,而不继承Cloneable接口,是一定有问题的,如果clone()方法只是简单进行克隆,如:new一个对象并初始化,然后返回这个新创建的对象的话,不继承Cloneable接口也是可以的。

2.如果是上面这样的话,为什么还要继承Cloneable接口呢?稍微说一下,Cloneable接口是不包含任何方法的!其实这个接口仅仅是一个标志,而且这个标志也仅仅是针对Object类中clone()方法的,如果clone类没有实现 Cloneable接口,并调用了Object的clone()方法(也就是调用了super.Clone()方法),那么Object的clone() 方法就会抛出CloneNotSupportedException异常。Cloneable用法

3.所以这里建议是:规范写法,如果重写clone(),最好继承Cloneable接口。

class MyTest implements Cloneable{

    public MyTest clone(){

        MyTest myTest = new MyTest();

        return myTest;          

    }           

}    

 

你可能感兴趣的:(Cloneable)