title: Java custom annotation that injects another object
body: <p>I am trying to learn how to write custom annotations in Java.</p>
  
  <p>For learning purposes, I decided to try to create an annotation that make a field available for a class using the annotation, ie: injection but not necessary as a singleton to keep it a bit more simple ( I think ), but that is welcome as well.</p>
  
  <p>=================================<strong>CLASS 1</strong>=================================</p>
  
  <pre><code>import java.lang.annotation.ElementType;
  import java.lang.annotation.Inherited;
  import java.lang.annotation.Retention;
  import java.lang.annotation.RetentionPolicy;
  import java.lang.annotation.Target;
  
  
  @Target(ElementType.METHOD)
  @Retention(RetentionPolicy.RUNTIME)
  @Inherited
  public @interface AutoInject {
  
  }
  </code></pre>
  
  <p>=================================<strong>CLASS 2</strong>=================================</p>
  
  <pre><code>// The class to be injected in Main.java
  public class TestClass0 {
  
      void printSomething(){
          System.out.println("PrintSomething: TestClass0");
      }
  
  }
  </code></pre>
  
  <p>=================================<strong>CLASS 3</strong>=================================</p>
  
  <pre><code>import java.lang.annotation.Annotation;
  import java.lang.reflect.Field;
  
  public class Main {
  
      TestClass0 ts0; 
      // Injecting here!!
      @AutoInject
      public TestClass0 getTso() {
          return ts0;
      }
      public void setTso(TestClass0 ts) {
          ts0 = ts;
      }
  
      public static void main(String[] args) {
          performAnnotationScanOnClass (Main.class);
  
          // Create instance 
          Main main = new Main();     
          main.getTso().printSomething();
  
      }
  
      public static void performAnnotationScanOnClass(Class&lt;?&gt; clazz) {
          Field[] fields = clazz.getDeclaredFields();
  
          for ( Field field : fields ) {
  
               Annotation[] annotations = field.getAnnotations();
               for (Annotation annotation : annotations) {
  
                   if ( annotation instanceof AutoInject ) {
                       AutoInject autoInject = (AutoInject) annotation;
  
  //                     if ( field.get( ... ) == null )
  //                         field.set( ... , value)
                   }
  
               }
  
          }
      }
  
  }
  </code></pre>
  
  <p>As you can see in the static void main() ... I am trying to call the method in TestClass0, expecting it to be available. I know that the above is long from near completion, but I just started learning annotations and would like your guidance. </p>
  
  <p>How can we fire a piece of code, that initializez a property either on <strong>new</strong> or when the <strong>get method</strong> is called. Using annotations. I am thinking <strong>without altering invoke</strong> method.</p>
  
  <p>Thanks!</p>