Java Getters and Setters

后端 未结 17 1497
终归单人心
终归单人心 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条回答
  • 2020-12-01 15:58

    I'm not sure if you'd consider it 'standard', but Project Lombok addresses this problem. They use annotations to replace much of the verbosity of Java.

    Some people are looking at alternative Java sibling languages, such as Groovy or Scala. I'm afraid it will take some years -if at all- before the JSR figures out a "standardized" way to "fix" this in Java proper.

    0 讨论(0)
  • 2020-12-01 15:58

    There is also Spring Roo project with its @RooJavaBean annotation. It has also @RooToString and @RooHashCodeEquals or something like that. It generates in background an AspectJ file with proper methods.

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

    Most IDEs provide a shortcut for generating the code (e.g. Eclipse: Right click -> Source -> Generate Getters & Setters), although I realise this is probably not the answer you are looking for.

    Some IOC frameworks allow you to annotate properties so that they can be used in the context of the framework e.g. Tapestry IOC, and the latest Spring, I think (but this use is limted to use by the framework)

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

    I agree that getter/setters are verbose. Project Lombok has good answer for it as suggested by others. Otherwise, you could use your IDE's capability to generate them.

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

    As a possible alternative, have you tried Scala? It compiles to Java bytecode, and has lots of interesting shortcuts which can make your life as a Java programmer easier.

    Properties for instance:

    case class Person(var name:String, 
                      var age:Int);
    val p = Person("John", 4)
    p.name
    p.name = "Charlie"
    p.name
    

    And the output:

    defined class Person
    p: Person = Person(John,4)
    res7: String = John
    res8: String = Charlie
    
    0 讨论(0)
  • 2020-12-01 16:05

    Yeah, you are kind of out of luck. Groovy does generate them for you, but no dice in standard java. If you use Eclipse you can generate them pretty easily, as well as generate hashCode() and equals() functions.

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