title: How do I identify immutable objects in Java
body: <p>In my code, I am creating a collection of objects which will be accessed by various threads in a fashion that is only safe if the objects are immutable. When an attempt is made to insert a new object into my collection, I want to test to see if it is immutable (if not, I'll throw an exception).</p>
  
  <p>One thing I can do is to check a few well-known immutable types:</p>
  
  <pre><code>private static final Set&lt;Class&gt; knownImmutables = new HashSet&lt;Class&gt;(Arrays.asList(
          String.class, Byte.class, Short.class, Integer.class, Long.class,
          Float.class, Double.class, Boolean.class, BigInteger.class, BigDecimal.class
  ));
  
  ...
  
  public static boolean isImmutable(Object o) {
      return knownImmutables.contains(o.getClass());
  }
  </code></pre>
  
  <p>This actually gets me 90% of the way, but sometimes my users will want to create simple immutable types of their own:</p>
  
  <pre><code>public class ImmutableRectangle {
      private final int width;
      private final int height;
      public ImmutableRectangle(int width, int height) {
          this.width = width;
          this.height = height;
      }
      public int getWidth() { return width; }
      public int getHeight() { return height; }
  }
  </code></pre>
  
  <p>Is there some way (perhaps using reflection) that I could reliably detect whether a class is immutable? False positives (thinking it's immutable when it isn't) are not acceptable but false negatives (thinking it's mutable when it isn't) are.</p>
  
  <p><strong>Edited to add:</strong> Thanks for the insightful and helpful answers. As some of the answers pointed out, I neglected to define my security objectives. The threat here is clueless developers -- this is a piece of framework code that will be used by large numbers of people who know next-to-nothing about threading and won't be reading the documentation. I do NOT need to defend against malicious developers -- anyone clever enough to <a href="http://directwebremoting.org/blog/joe/2005/05/26/1117108773674.html" rel="noreferrer">mutate a String</a> or perform other shenanigans will also be smart enough to know it's not safe in this case. Static analysis of the codebase IS an option, so long as it is automated, but code reviews cannot be counted on because there is no guarantee every review will have threading-savvy reviewers.</p>