How to automatically generate getters and setters in Android Studio

后端 未结 15 1142
太阳男子
太阳男子 2020-12-02 04:15

Is there a shortcut in Android Studio for automatically generating the getters and setters in a given class?

相关标签:
15条回答
  • 2020-12-02 04:55

    Using Alt+ Insert for Windows or Command+ N for Mac in the editor, you may easily generate getter and setter methods for any fields of your class. This has the same effect as using the Menu Bar -> Code -> Generate...

    enter image description here

    and then using shift or control button, select all the variables you need to add getters and setters

    0 讨论(0)
  • 2020-12-02 04:57

    Android Studio & Windows :

    fn + alt + insert

    0 讨论(0)
  • 2020-12-02 04:58

    This answer deals with your question but is not exactly an answer to it. =) It's an interesting library I found out recently and I want to share with you.


    Project Lombok can generate common methods, such as getters, setters, equals() and hashCode(), toString(), for your classes automatically. It replaces them with annotations reducing boilerplate code. To see a good example of code written using Lombok watch a video on the main page or read this article.

    Android development with Lombok is easy and won't make your android application any 'heavier' because Lombok is a compile-time only library. It is important to configure your Android project properly.

    Another example:

    import lombok.Getter;
    import lombok.Setter;
    
    public class Profile {
    
      @Getter @Setter
      private String username;
    
      @Getter @Setter
      private String password;
    
    }
    

    Android development with Lombok is possible. Lombok should be a compile-time only dependency, as otherwise the entirety of Lombok will end up in your DEX files, wasting precious space. Gradle snippet:

    dependencies {
        compileOnly "org.projectlombok:lombok:1.16.18"
    }
    

    In addition you may want to add the Lombok IntelliJ plugin to support Lombok features in your IDE at development time. Also there is Hrisey library which is based on Lombok. Simply put, it's Lombok + Parcellable support.

    0 讨论(0)
  • 2020-12-02 04:59

    use code=>generate=>getter() and setter() dialog ,select all the variables ,generate all the getter(),setter() methods at one time.

    0 讨论(0)
  • 2020-12-02 05:00

    Use Ctrl+Enter on Mac to get list of options to generate setter, getter, constructor etc

    0 讨论(0)
  • 2020-12-02 05:05

    Position the cursor under the variables -> right-click -> Generate -> Getter and Setter -> Choose the variables to make the get and set

    or

    Alt + Insert -> Getter and Setter -> Choose the variables

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