有时我会想念使用IDE的懒惰,让我只需编写Java类的属性,然后让IDE生成所需的getter/setter.
Emacs可以这样做吗?
目前我只是复制粘贴前一行的一对getter/setter,然后复制粘贴并修改它.这很简单,但是,编码有点有趣:)
Che*_*eso 12
您特别询问了如何生成getter/setter对.你可以写elisp来做这件事.但是研究更通用的解决方案可能会很有趣.
为了解决这个问题,我使用了ya-snippet.该名称是指"又一个Snippet软件包",因此您可以确定问题已经解决过.但我发现ya-snippet是最有用,最简单,最有效的解决方案,可满足我的需求.
对于带有getter/setter的属性,我输入
prop<TAB>
Run Code Online (Sandbox Code Playgroud)
...然后我得到一个模板,然后我可以填写,就像表格一样.我指定属性的名称,并生成其他所有内容.很好,很容易.

这适用于您在代码中常用的任何微图案.我有一个单例,构造函数,for循环,switch语句,try/catch等的代码片段.
ya-snippet的关键是没有要编写的elisp代码.基本上我只是提供模板的文本,它的工作原理.这是您在上面看到的getter/setter片段的ya-snippet代码:
# name : getter/setter property ... { ... }
# key: prop
# --
private ${1:Type} _${2:Name};
public ${1:Type} get$2 {
${3://get impl}
}
public void set$2($1 value) {
${4://set impl}
}
Run Code Online (Sandbox Code Playgroud)
"# - "之上的所有内容都是剪辑的元数据."密钥"是元数据中最重要的部分 - 它是可以扩展的短序列.该名称显示在yasnippet菜单上.该# --行下面的东西是扩展代码.它包括几个填写字段.
YAsnippet适用于emacs(java,php,c#,python等)中的任何编程模式,它也适用于其他文本模式.
我也在使用yasnippet,但这是一个更好的片段,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
Run Code Online (Sandbox Code Playgroud)
该代码中,例如在10次击键生成(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; }
Run Code Online (Sandbox Code Playgroud)
我建议绑定yas/expand C-o而不是TAB以避免与自动完成冲突.我有这个设置:
(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))))
Run Code Online (Sandbox Code Playgroud)
请注意(expand-abbrev)此代码中的某处.它让我扩大例如bis到BufferedInputStream时候我定义:
(define-abbrev-table 'java-mode-abbrev-table
'(
("bb" "ByteBuffer" nil 1)
("bis" "BufferedInputStream" nil 1)
%...
))
Run Code Online (Sandbox Code Playgroud)