Java get value from custom annotation

The annotation class,

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

@interface Person {
    String name();
    int age();

The dummpy Room class with a method that uses the Person annotation,

public class Room {
    @Person(name = "Jamie", age=21)
    public void getPerson() {

The main class to execute the code, demonstrating how to get the annotation values.

import java.lang.reflect.Method;
public class Demo {
    public static void main(String[] args) {
        try {
            Method m = Room.class.getMethod("getPerson");
            Person personAnnotation = (Person) m.getAnnotation(Person.class);
            if (personAnnotation != null) {
                    System.out.println(" Name : " +;
                    System.out.println(" Age : " + personAnnotation.age());
                    System.out.println(" --------------------------- ");
        } catch (NoSuchMethodException e) {

To compile and run from the command line provided all of the above are in one folder.

java Demo

The output
Name : Jamie
Age : 21

Search within Codexpedia

Custom Search

Search the entire web

Custom Search