I've created a simple Getter generator to generate an "Optional-Getter" which wraps the field inside an Optional. the problem is when the field is annotate as @Nullable the getter will also generated with @Nullable and I found that very annoying to simply remove it every time I'm generating a getter. How can I ignore the field annotation in a costume getter ?
This is my "Optional-Getter" generator.
#if($field.modifierStatic)
static ##
#end
Optional<$field.type> ##
#set($name = $StringUtil.capitalizeWithJavaBeanConvention($StringUtil.sanitizeJavaIdentifier($helper.getPropertyName($field, $project))))
#if ($field.boolean && $field.primitive)
is##
#else
get##
#end
${name}() {
return Optional.fromNullable($field.name);
}
and that's the result now when I'm generating a getter -
public class Class {
@Nullable
private String someMember;
@Nullable
public Optional<String> getSomeMember() {
return Optional.fromNullable(someMember);
}
}
that's the expected result -
public class Class {
@Nullable
private String someMember;
public Optional<String> getSomeMember() {
return Optional.fromNullable(someMember);
}
}
Get the plugin CodeGenerator, via their GitHub Repository > Releases
.
The latest relase is 1.3.3
Install the Plugin "from disk", re-start IntelliJ/Android Studio, then via Settings > CodeGenerator
, modify the default Getter and Setter
template with this code, and enable it
#foreach($field in $fields)
#set($name = $StringUtil.capitalizeWithJavaBeanConvention($StringUtil.sanitizeJavaIdentifier($helper.getPropertyName($field.element, $project))))
#if ($field.boolean && $field.primitive)
#set($getter = "is${name}")
#else
#set($getter = "get${name}")
#end
#set($setter = "set${name}")
#if($field.modifierStatic)
static ##
#end
#if($field.modifierStatic)
static ##
#end
Optional<$field.type> ##
${getter}() {
return Optional.fromNullable($field.name);
}
#if($field.modifierStatic)
static ##
#end
void ${setter}($field.type $paramName) {
#if ($field.name == $paramName)
#if (!$field.modifierStatic)
this.##
#else
$classname.##
#end
#end
$field.name = $paramName;
}
#end
You can than use it via Alt+ins
(or Code > Generate
)
Customize your templates as needed, or add new ones. Enjoy ;)
That's something I was looking at too for IDEA. Actually since a long time. Unfortunately as of now it doesn't seem to be parameterizable.
This is the YouTrack issue which made available the automatic insertion of @Nullable
and @NotNull
to generated getters/setters
https://youtrack.jetbrains.net/issue/IDEA-30683
You can vote for a feature that would automatically convert to an Optional<T>
getter, when possible
https://youtrack.jetbrains.net/issue/IDEA-201804
And you can vote for the feature that exposes the annotations to the Apache Velocity template