0

I have a method like

Bar yieldBar(Foo foo) {
    Bar bar = new Bar();
    bar.setFoo(foo);
    return bar;
}

And I want this call to simply return null if foo is null. Is there a way to implement something like

@NullPassthrough
Bar yieldBar(Foo foo) {
    ...
}

Which would be equivalent to below through some compile time generated wrapper:

Bar yieldBar(Foo foo) {
    if (foo == null) return null;
    return yieldBar(foo);
}

Bar yieldBarHelper(Foo foo) {
    ...
}
Layman
  • 597
  • 3
  • 16
  • 1
    You could go down the way Spring does with AOP, by creating a wrapper-class at runtime. But this would mean one would have to use a DI framework to create and inject beans. – Turing85 Jan 10 '20 at 17:40

2 Answers2

0

Firstly, the usage of annotations within Java is purely for syntactic meta data reasons, so for specifying whether a method returns null will not function in this manner.

Another usage would be for specifying additional actions for the compiler when utilising annotations.

  • The latter is what I am thinking. Mapstruct, Lombok etc. utilize compile time processing to generate code – Layman Jan 10 '20 at 19:09
0

You don't need any annotation here, and i will say if argument foo is null then there is no use of calling yieldBar method, you can avoid calling using ternary operator

Bar bar = Objects.nonNull(foo) ? yieldBar(foo) : null;
Deadpool
  • 33,221
  • 11
  • 51
  • 91