Can IntelliJ generate getters without the “get” prefix?

◇◆丶佛笑我妖孽 提交于 2019-12-05 16:53:10

问题


IntelliJ has the cool feature to generate Java getters. For example, for a field private final String foo, it will generate a getter getFoo().

Is there any way I can configure IntelliJ to generate getters in the format String foo()? I am working mainly with immutable objects and prefer this syntax.


回答1:


Neat question! Just to clarify @Danny Dan's answer since IntelliJ 15 has been released...

To set this up:

  • Alt+Insert
  • Select Getter
  • Open the template configuration from '...' on the RHS
  • Create a new template from the LHS - see example below
  • Ok and select your new template

Example Template: fluent-getter

 public ##
 #if($field.modifierStatic)
   static ##
 #end
 $field.type ##
 ${field.name}() {
   return $field.name;
 }

Why would you want to do this?

Checkout Implementing Domain-Driven Design:

The simple but effective approach to object design keeps the Value Object faithful to the Ubiquitous Language. The use of getValuePercentage() is a technical computer statement, but valuePercentage() is a fluent human-readable language expression.




回答2:


If I understood right you cannot modify getters/setters in idea now. Issue on youtrack

P.S. Ok, now Fix version is 14.1, from this version of idea you can create and choose getter/setter template directly in Alt-Insert menu.




回答3:


Here are some slightly improved templates based on @Ed .'s previous answer:

fluent-getter:

public ##
#if($field.modifierStatic)
  static ##
#end
$field.type ##
${field.name}() {
return ##
#if (!$field.modifierStatic)
this.##
#else
  $classname.##
#end
$field.name;
}

fluent-setter:

#set($paramName = $helper.getParamName($field, $project))
public ##
#if($field.modifierStatic)
  static ##
#end
void ##
${field.name}($field.type $paramName) {
#if ($field.name == $paramName)
  #if (!$field.modifierStatic)
  this.##
  #else
    $classname.##
  #end
#end
$field.name = $paramName;
}


来源:https://stackoverflow.com/questions/26556659/can-intellij-generate-getters-without-the-get-prefix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!