Generating getter method with Optional as a return type by annotation using Groovy and AST transformations.
Let's assume you have class like this:
class Foo {
private String someField
}
And you want to have method Optional<String> getSomeFieldOptional()
Sounds like a boilerplate, huh?
Well, put @OptionalGetter
on field and enjoy the magic of AST transformations :)
class Foo {
@OptionalGetter
private String someField
}
As of result of AST transformation you will have .class similar to:
public class Foo implements GroovyObject {
private String someField;
// generated constructor omitted
public Optional<String> getSomeFieldOptional() {
CallSite[] var1 = $getCallSiteArray();
return (Optional) ScriptBytecodeAdapter.castToType(var1[0].callStatic(Optional.class, this.someField), Optional.class);
}
}
- Add to your build.gradle:
allprojects {
repositories {
maven { url 'https://jitpack.io' }
}
}
- Add dependency:
dependencies {
implementation 'com.github.eugenelesnov:optional-getter:1.0'
}
Well, there are plans...
- Fixing possible bugs
- IDE support. Of course, Intelij IDEA is a priority ;) For now, it works for Groovy only. There is no way (yet!) to use this library with Java because IDE won't let you use the method generated at the compile-time..