How to create custom IntelliJ getter template for nullable field with JDK8 Optional

Viewed 947

I'm trying to create a custom IntelliJ template that makes use of JDK8 Optional. If a field is annotated with @Nullable I want to use Optional as getter.

Instead of this (with default getter template):

@Nullable
private final String name;

public String getName() {
    return name;
}

I want this:

@Nullable
private final String name;

public java.util.Optional<String> getName() {
    return java.util.Optional.ofNullable(name);
}

I've kept the full package name since the IDE would then hopefully import the right Optional (and not Guava's).

Here's what I've so far:

#if($field.modifierStatic)
static ##
#end
$field.type ##
#set($name = $StringUtil.capitalizeWithJavaBeanConvention($StringUtil.sanitizeJavaIdentifier($helper.getPropertyName($field, $project))))
#if ($field.boolean && $field.primitive)
  is##
#else
  get##
#end
${name}() {
  #if ($field.getAnnotation(javax.annotation.Nullable.class))
    return Optional.ofNullable($field.name);
  #else  
    return $field.name;
  #end  
}

getAnnotation(javax.annotation.Nullable.class) doesn't appear to work. Also missing is using Optional<String> instead of String.

I'm using the javax.annotation.Nullable annotation but ideally it would work with any of the configured annotations:

enter image description here

1 Answers

That's how I have it configured. I have a getter template named Optional getter:

#if($field.modifierStatic)
static ##
#end
Optional<$field.type> ##
#if($field.recordComponent)
  ${field.name}##
#else
#set($name = $StringUtil.capitalizeWithJavaBeanConvention($StringUtil.sanitizeJavaIdentifier($helper.getPropertyName($field, $project))))
#if ($field.boolean && $field.primitive)
  is##
#else
  get##
#end
${name}##
#end
() {
  return Optional.ofNullable($field.name);
}

I normally use Lombok for getters, that's why I can have that template selected all the time. Below is thie window which popups on Generate... -> Getter:

enter image description here

When I have this selected, then I can just start typing getSomething... and the a popup will appear:

enter image description here

After hitting enter the following code is inserted:

enter image description here

Related