Joke Collection Website - Mood Talk - Java, how to use custom annotations

Java, how to use custom annotations

How to use custom annotations in Java:

First declare an interface and add annotation content to it!

package testAnnotation;

import java.lang.annotation.Documented;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

@Documented

@Retention(RetentionPolicy.RUNTIME)

public @interface Person{

String name();

int age();

}

2. Then use the reflection mechanism to view the annotation content of the class

package testAnnotation;

@Person(name="xingoo",age=25)

public class test3 {

public static void print(Class c){

System.out.println(c.getName());

//The getAnnotation method of java.lang.Class returns the annotation if there is an annotation. Otherwise return null

Person person = (Person)c.getAnnotation(Person.class);

if(person != null){

System.out .println("name:"+person.name()+" age:"+person.age());

}else{

System.out.println(" person unknown!");

}

}

public static void main(String[] args){

test3.print (test3.class);

}

}

Run the results and read the content of the annotation

testAnnotation.test3

name:xingoo age:25