heyimMarc
11/22/2017 - 3:24 PM

@Helper With a little help from my friends... Helper methods for java.

This annotation lets you put methods in methods. You might not know this, but you can declare classes inside methods, and the methods in this class can access any (effectively) final local variable or parameter defined and set before the declaration. Unfortunately, to actually call any methods you'd have to make an instance of this method local class first, but that's where @Helper comes in and helps you out! Annotate a method local class with @Helper and it's as if all the methods in that helper class are methods that you can call directly, just as if java had allowed methods to exist inside methods.

Normally you'd have to declare an instance of your helper, for example: HelperClass h = new HelperClass(); directly after declaring your helper class, and then call methods in your helper class with h.helperMethod();. With @Helper, both of these things are no longer needed: You do not need to waste a line of code declaring an instance of the helper, and you don't need to prefix all your calls to helper methods with nameOfHelperInstance.

import lombok.experimental.Helper;

public class HelperExample {
  int someMethod(int arg1) {
    int localVar = 5;

    @Helper class Helpers {
      int helperMethod(int arg) {
        return arg + localVar;
      }
    }

    return helperMethod(10);
  }
}