Reports return of, or assignment from a method parameter to a field of an array or a mutable type such as Collection, Date, Map, Calendar, etc.

このような型はミュータブルであるため、このコンストラクトが原因で所有クラス外からの予期しないオブジェクトの状態変更が発生する可能性があります。 このコンストラクトはパフォーマンスの面では有益ですが、本質的にバグを引き起こす可能性があります。

次のミュータブルな型が報告されます:

The quick-fix adds a call to the field's .clone() method for arrays or uses an unmodifiable collection wrapper.

例:


  import java.util.*;
  class Log {
    private String[] messages = {"one", "two", "three"};
    private Map<String, String> map = new HashMap<>();

    String[] getMessages() {
      return messages; // warning: Return of String[] field 'messages'
    }

    Map<String, String> mapping() {
      return map; // warning: Return of Map<String, String> field 'map'
    }
  }

クイックフィックス適用後:


  import java.util.*;
  class Log {
    String[] messages = {"one", "two", "three"};
    private Map<String, String> map = new HashMap<>();

    String[] getMessages() {
      return messages.clone();
    }

    Map<String, String> mapping() {
      return Collections.unmodifiableMap(map);
    }
  }

private メソッド内の代入と返却を無視するには、「private メソッドでの代入および private メソッドからの返却を無視する」オプションを使用します。