How do I identify immutable objects in Java

后端 未结 15 1372
小蘑菇
小蘑菇 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:15

    You Can Ask your clients to add metadata (annotations) and check them at runtime with reflection, like this:

    Metadata:

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.CLASS)
    public @interface Immutable{ }
    

    Client Code:

    @Immutable
    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; }
    }
    

    Then by using reflection on the class, check if it has the annotation (I would paste the code but its boilerplate and can be found easily online)

提交回复
热议问题