Java Getters and Setters

后端 未结 17 1499
终归单人心
终归单人心 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 16:17

    I've created some annotations that are not eclipse-specific.

    See http://code.google.com/p/javadude/wiki/Annotations

    For example:

    package sample;
    
    import com.javadude.annotation.Bean;
    import com.javadude.annotation.Property;
    import com.javadude.annotation.PropertyKind;
    
    @Bean(properties={
        @Property(name="name"),
        @Property(name="phone", bound=true),
        @Property(name="friend", type=Person.class, kind=PropertyKind.LIST)
    }) 
    public class Person extends PersonGen {
    }
    

    My annotations generate a superclass; I think Lombok modifies the actual class being compiled (which is officially not supported by Sun and may break - I could be wrong about how it works, but based on what I've seen they must be doing that)

    Enjoy! -- Scott

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

    With Netbeans, just start typing get or set where the getter/setter is to be replaced and call up auto complete (Ctrl+Space), it'll give you the option to generate the getter or setter. It'll also give you an option to generate a constructor as well.

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

    In the case that you need a read-only class, take a look at Java Records. It auto-generates getters and methods like equals and hashcode. However, this feature is not stabilized and currently you can use it as an experimental feature (Probably will be stabilized on Java 16). https://dzone.com/articles/introducing-java-record

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

    Use your IDE to generate it for you and try to minimize the amount of getters/ setters that you have - you will likely enjoy the added benefit of immutability.

    I like the C# syntax for properties, I think it's pretty and clean, and pretty clean.

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

    That's the work of the IDE to generate repetitive verbose code as getters/setters

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