How do I identify immutable objects in Java

后端 未结 15 1220
小蘑菇
小蘑菇 2020-11-30 22:40

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 m

15条回答
  •  有刺的猬
    2020-11-30 23:04

    Like the other answerers already said, IMHO there is no reliable way to find out if an object is really immutable.

    I would just introduce an interface "Immutable" to check against when appending. This works as a hint that only immutable objects should be inserted for whatever reason you're doing it.

    interface Immutable {}
    
    class MyImmutable implements Immutable{...}
    
    public void add(Object o) {
      if (!(o instanceof Immutable) && !checkIsImmutableBasePrimitive(o))
        throw new IllegalArgumentException("o is not immutable!");
      ...
    }
    

提交回复
热议问题