Java Reflection method get annotation

Description

Java Reflection method get annotation

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;

@Target(value = ElementType.METHOD)
@Retention(value = RetentionPolicy.RUNTIME)
@interface Marker {
}

class X {/*from ww  w .j a va  2  s.c o  m*/
   public void a() {
      System.out.println("a() called");
   }

   @Marker
   public void b() {
      System.out.println("b() called");
   }

   @Marker
   public void c() {
      System.out.println("c() called");
   }
}

public class Main {
   public static void main(String args[]) throws Exception {
      X x = new X();
      Method[] methods = x.getClass().getDeclaredMethods();
      for (Method method : methods) {
         Marker c = method.getAnnotation(Marker.class);
         if (c != null) {
            try {
               method.invoke(x);
            } catch (Exception e) {
               e.printStackTrace();
            }
         }
      }
   }
}



PreviousNext

Related