How to implement a 'generate getter/setter' for a Java Class in emacs?

后端 未结 4 789
别跟我提以往
别跟我提以往 2021-02-07 10:27

Sometimes I miss the laziness of using an IDE that let me just write the attribute of a Java class and then let the IDE generate the required getter/setter.

Can Emacs do

4条回答
  •  遇见更好的自我
    2021-02-07 10:40

    I'm using yasnippet as well, but this is a better snippet, imho:

    # -*- mode: snippet -*-
    # name: property
    # key: r
    # --
    private ${1:T} ${2:value};
    public $1 get${2:$(capitalize text)}() { return $2; }
    public void set${2:$(capitalize text)}($1 $2) { this.$2 = $2; }
     $0
    

    This code, for instance is generated in 10 keystrokes (r, C-o, Long, C-o, id, C-o):

    private Long id;
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    

    I recommend binding yas/expand to C-o and not TAB to avoid clashes with e.g. auto-complete. I have this setup:

    (global-set-key "\C-o" 'open-line-or-yas)
    (defun open-line-or-yas ()
      (interactive)
      (cond ((and (looking-back " ") (looking-at "[\s\n}]+"))
         (insert "\n\n")
         (indent-according-to-mode)
         (previous-line)
         (indent-according-to-mode))
        ((expand-abbrev))
        (t 
         (setq *yas-invokation-point* (point))
         (yas/next-field-or-maybe-expand-1))))
    (defun yas/next-field-or-maybe-expand-1 ()
      (interactive)
      (let ((yas/fallback-behavior 'return-nil))
        (unless (yas/expand)
          (yas/next-field))))
    

    Note (expand-abbrev) somewhere inside this code. It allows me to expand e.g. bis to BufferedInputStream when I define:

    (define-abbrev-table 'java-mode-abbrev-table
      '(
        ("bb" "ByteBuffer" nil 1)
        ("bis" "BufferedInputStream" nil 1)
        %...
    ))
    

提交回复
热议问题