title: How to add runtime functionality to annotation types in Java?
body: <p>I'm trying to understand the use cases of annotations. I read e.g. the <a href="https://docs.oracle.com/javase/tutorial/java/annotations/index.html" rel="nofollow">Oracle Annotations Tutorial</a> and some other resources. One type of examples that was always missing is, how to actually add functionality for annotations.</p>
  
  <p>Let's say I'd like to have an annotation <code>@SetValueIfNull</code> that assigns/returns a given value when fields, parameters or methods equal/return <code>null</code>.</p>
  
  <p>My annotation could be:</p>
  
  <pre><code>package com.stackoverflow.tests.annotations;
  
  /**
   * Replaces null in fields, parameters and methods.
   */
  public @interface SetValueIfNull {
    /**
     * Value used to replace null.
     */
    String replacement() default "";
  }
  </code></pre>
  
  <p>And here an example of it's usage:</p>
  
  <pre><code>package com.stackoverflow.tests.annotations;
  
  public class ReplaceNull {
  
    @SetValueIfNull(replacement = "Peter")
    private String name;
  
    public static void main(String[] args) {
      ReplaceNull o = new ReplaceNull();
  
      // This should print "Peter"
      System.out.println(o.getName());
  
      // This should print "Julie"
      o.setName(null);
      System.out.println(o.getName());
  
      // This should print "John"
      o.setName("John");
      System.out.println(o.getName());
  
      // This should print "Margaret"
      System.out.println(o.maggy());
  
    }
  
    String getName() {
      return this.name;
    }
  
    void setName(@SetValueIfNull(replacement = "Julie") String n) {
      this.name = n;
    }
  
    @SetValueIfNull(replacement = "Margaret")
    String maggy() {
      return null;
    }
  
  }
  </code></pre>
  
  <p>The only buzzwords that popped up from time to time were "use reflection (or compiler plugins)". I guess compiler plugins are not the way to go for runtime functionality (besides that I have no idea how to write compiler plugins).</p>
  
  <p>So is there an easy solution for my example or would I have to develop/use a whole framework for that?</p>