C Books Guide and List
C++ Books Guide and List
Best Java Books

3,749 questions

4,049 answers

114 comments

10,705 users

How to obtaining Annotations at Run Time by Use of Reflection?

0 votes
26 views
asked Apr 27, 2014 by omari Sr Member (3,860 points)

1 Answer

0 votes
 
 
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
// An annotation type declaration. 
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
  String str();
 
  int val();
}
 
public class Main {
  @MyAnno(str = "Annotation Example", val = 100)
  public static void myMeth() {
    Main ob = new Main();
    try {
      Class c = ob.getClass();
      Method m = c.getMethod("myMeth");
      MyAnno anno = m.getAnnotation(MyAnno.class);
      System.out.println(anno.str() + " " + anno.val());
    } catch (NoSuchMethodException exc) {
      System.out.println("Method Not Found.");
    }
  }
  public static void main(String args[]) {
    myMeth();
  }
}
 
 
 
answered Apr 27, 2014 by felin Advisor (8,400 points)

Related questions

0 votes
1 answer 20 views
20 views asked Apr 27, 2014 by omari Sr Member (3,860 points)
0 votes
1 answer 18 views
18 views asked Mar 15, 2014 by rock Expert (14,990 points)
0 votes
0 answers 50 views
50 views asked Oct 29, 2010 by anonymous
0 votes
1 answer 13 views
13 views asked Apr 27, 2014 by omari Sr Member (3,860 points)
0 votes
1 answer 14 views
14 views asked Apr 27, 2014 by sunny Expert (11,410 points)
...