Java Getters and Setters

后端 未结 17 1498
终归单人心
终归单人心 2020-12-01 15:27

Is there a better standard way to create getters and setters in Java?

It is quite verbose to have to explicitly define getters and setters for each variable. Is ther

相关标签:
17条回答
  • If you use emacs it might be possible to define an emacs macro that does this for you. Any emacs gurus out there? :)

    0 讨论(0)
  • 2020-12-01 16:09

    Eclipse has a context menu option that will auto-generate these for you, as I am sure many other IDE's do.

    0 讨论(0)
  • 2020-12-01 16:10

    Here is an interesting articles about the subject: http://cafe.elharo.com/java/why-java-doesnt-need-properties-it-already-has-them/

    I think properties are a shortcut but it's more a little feature than a real important feature

    0 讨论(0)
  • 2020-12-01 16:10

    Well, one option is don't be so afraid of public fields. For simple classes that you know will never do validation or extra work under the hood on get and set, public fields require less boilerplate, are syntactically nicer, and are more efficient.

    0 讨论(0)
  • 2020-12-01 16:11

    Try something like this:

    @Getter @Setter private int age = 10;

    More info below:

    https://projectlombok.org/features/GetterSetter

    0 讨论(0)
  • 2020-12-01 16:16

    There is no better way that's part of the language -- nothing like a "property" keyword.

    One alternative, as other people have mentioned, is to use your IDE to generate them. Another, if you have a lot of objects that need this, is to write your own code generation tool that takes a base class and produces a wrapper with getters and setters.

    You could also simply expose the variables as public members. However, down the road this will probably come back to hurt you, when you decide to add validation logic.

    However, one final thought: unless your classes are used simply to transfer data, they probably shouldn't expose their internal state. IMO, "behavior" classes with getters and setters are a code smell.

    0 讨论(0)
提交回复
热议问题