Method annotation

In this chapter you will learn:

  1. How to get annotation for method

Annotation for method

The following code gets a method from its class by using getMethod and pass in myMeth. Then it gets annotation by annotation class name.

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
/*from   ja  va 2s .  c o  m*/
@Retention(RetentionPolicy.RUNTIME)
@interface MySingle {
  int value(); // this variable name must be value
}

public class Main {
  @MySingle(100)
  public static void myMeth() {
    Main ob = new Main();

    try {
      Method m = ob.getClass().getMethod("myMeth");

      MySingle anno = m.getAnnotation(MySingle.class);

      System.out.println(anno.value()); // displays 100

    } catch (NoSuchMethodException exc) {
      System.out.println("Method Not Found.");
    }
  }

  public static void main(String args[]) {
    myMeth();
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Locale class
  2. How to use Locale to set date format for a country
  3. Sets the default locale for this instance of the Java Virtual Machine
Home » Java Tutorial » Reflection
Reflection
Class Reflection
Class modifier, package and string presentation
Constructor reflection
Field Reflection
Get/Set field value
Java method reflection
Modifier
Package
Array reflection
Get annotation type
Method annotation