Why shouldn't I use immutable POJOs instead of JavaBeans?

前端 未结 7 1338
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-04 06:27

I have implemented a few Java applications now, only desktop applications so far. I prefer to use immutable objects for passing the data around in the application instead of

7条回答
  •  星月不相逢
    2020-12-04 07:06

    From Java 7 you can have immutable beans, the best of both worlds. Use the annotation @ConstructorProperties on your constructor.

    public class Person {
        private final String name;
        private final Place birthPlace;
    
        @ConstructorProperties({"name", "birthPlace"})
        public Person(String name, Place birthPlace) {
            this.name = name;
            this.birthPlace = birthPlace;
        }
    
        public String getName() {
            return name;
        }
    
        public Place getBirthPlace() {
            return birthPlace;
        }
    }
    

提交回复
热议问题