Java get value from custom annotation
The annotation class, Person.java
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @interface Person { String name(); int age(); }
The dummpy Room class with a method that uses the Person annotation, Room.java
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. Demo.java
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 : " + personAnnotation.name()); System.out.println(" Age : " + personAnnotation.age()); System.out.println(" --------------------------- "); } } catch (NoSuchMethodException e) { System.out.println("NoSuchMethodException"); return; } } }
To compile and run from the command line provided all of the above are in one folder.
javac Demo.java java Demo
The output
Name : Jamie
Age : 21
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts