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:



