-1

I'm working in an old project with some old code and findbug is giving the following error with a byte[].

FindBugs: May expose internal representation by incorporating reference to mutable object This code stores a reference to an externally mutable object into the internal representation of the object.  If instances are accessed by untrusted code, and u nchecked changes to the mutable object would compromise security or other important properties, you will need to do something different. Storing a copy of the object is better approach in many situations.

I'm wondering if someone could help me to understand the proper way to handle this error?

private byte[] fileContent;

public FileUpload(String fileName, String fileExtension, long fileSize, byte[] fileContent, boolean attachedToPo, boolean programOwner) {
        this.fileName = fileName;
        this.fileExtension = fileExtension;
        this.fileSize = fileSize;
        this.fileContent = fileContent;
        this.attachedToPo = attachedToPo;
        this.programOwner = programOwner;
    }

public byte[] getFileContent() {
    return fileContent;
}

public void setFileContent(byte[] fileContent) {
    this.fileContent = fileContent;
}

EDIT I understand why the bug exist and I know how to deal with this when it comes to dates etc. I'm just a little confused with how to deal with it when it comes to byte[].

Code Junkie
  • 7,602
  • 26
  • 79
  • 141
  • check all usages of getFileContent() and see how the result byte array is used. If it is not modified, then no fix required. – Alexei Kaigorodov Jan 09 '19 at 17:02
  • your object byte is a mutable element, it means if you return that object by modifying in other part of code will be modified also in your class. in other words it works as by reference, to avoid this problem return a copy of your object insteaf of your object – FarukT Jan 09 '19 at 17:02
  • In order to fix warning, you need to update setter to: ```this.fileContent = (fileContent == null) ? null : fileContent.clone();``` – Leonid Dashko Jul 28 '20 at 11:47

1 Answers1

2

getFileContent() return the byte array you are storing internally. Another class that get's this may start to modify it, and thus changing the byte array within your original class too. getFileContent() should return a copy of the array, instead of the array instance itself.