1. 程式人生 > >Findbugs中的BUG:May expose internal representation by returning reference to mutable object 引發問題說明

Findbugs中的BUG:May expose internal representation by returning reference to mutable object 引發問題說明

在使用IDEA的findbugs的外掛檢測model層類的時候發生如下錯誤:

May expose internal representation by returning reference to mutable object
Returning a reference to a mutable object value stored in one of the object's fields exposes the internal representation of the object.  If instances are accessed by untrusted code, and unchecked changes to the mutable object would compromise security or other important properties, you will need to do something different. Returning a new copy of the object is better approach in many situations.

這裡提示的BUG的測試結果如下:

實體類BusGeologicalDrilling部分程式碼:

public class BusGeologicalDrilling{
 private Date enddt;

// 此處省略建構函式


//下面為IDE自動為我們生成的get和set方法

 public Date getEnddt() {
        return   enddt  ;
    }

 public void setEnddt(Date enddt) {
        this.enddt =   enddt  ;
    }
}

部分測試程式碼如下:

 BusGeologicalDrilling busGeologicalDrilling=new BusGeologicalDrilling();
 Date date=new Date();
 busGeologicalDrilling.setEnddt(date);
 System.out.println(busGeologicalDrilling.getEnddt().toString());
 date.setYear(5);
 System.out.println(busGeologicalDrilling.getEnddt().toString());

測試結果如下:

通過結果對比發現:

日期的物件在經過改變後,原本之前賦予實體的enddt屬性的值也跟著被修改掉了,這樣顯然是不對的,這裡涉及到引用傳遞值的問題。此處不再深究。

解決方案:

一:修改實體的屬性的get和set方法如下:

public class BusGeologicalDrilling{
 private Date enddt;

// 此處省略建構函式


//下面為IDE自動為我們生成的get和set方法

 public Date getEnddt() {
        return (Date)enddt.clone();
    }

 public void setEnddt(Date enddt) {
        this.enddt = (Date)enddt.clone();
    }
}

備註:這種方式雖然可以解決引用值傳遞的問題,但是當在屬性上使用【com.fasterxml.jackson.annotation包下面的JsonFormat】如:註解控制Date的格式或者時區,如果當前屬性繫結的是非格式或者空值會發生繫結錯誤,所以此種方法並不完美,如下:

 @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
 private Date enddt;

二、使用官方推薦的Date獲取方式為實體進行賦值,測試如下:

上面測試我們看到是沒有任何問題的,原因在於Calendar類和Date的實體獲取機制不同導致。