Java Beans: What am I missing?

前端 未结 5 1947
别跟我提以往
别跟我提以往 2021-02-07 06:08

I\'m wondering if I\'m missing something about Java Beans. I like my objects to do as much initialization in the constructor as possible and have a minimum number of mutators. B

5条回答
  •  你的背包
    2021-02-07 06:36

    When you hear the word "bean" expect to be looking at a "container" of some sort. The idea of a JavaBean of any sort is to provide a uniform interface convention for components that can be added and manipulated at run time. Plain JavaBeans are just the simplest example of this: it presents all the interface possibilities and is Serializable, which means you can create instances of the bean, modify them, save them, and reload them.

    Long and long ago, I write a Java editor that contained a simple "data base" representing the text strings, and had a "plug in architecture" that used beans. You could add behavior to the editor by dragging a bean out of a bean storage bin and dropping it on the editor; once you did, the behavior (say, Cntl-T to transpose characters at cursor) was automagically available in the editor. The beans had a known interface --- they knew how to ask the container for its data structure, and a doSomething() method --- and the container knew to dynamically load a class file, instantiate the object, and set its access to the data base.

    By the way, it's not really necessarily true that accessors violate encapsulation; it is however true that just because you have a member, you don't need to provide get and set methods for it. The JavaBean spec is a little unclear on this; the point is to provide getters and setters for those things that need to be in the objects "contract".

    After introspection and reflection were added to the language and really understood, the need for those conventions was somewhat reduced; in early Java, you needed to have a convention to find the methods.

提交回复
热议问题