自定义注解

/**
 * @author Pickle
 * @version V1.0
 * @date 2024/3/12 14:01
 */
public @interface MyBook {
    String name();
    String[] authors();
    double prices();
}

元注解

  • @Target:约束自定义注解只能在那些地方使用
  • @Retention:申明注解的生命周期

注解的解析

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

/**
 * @author Pickle
 * @version V1.0
 * @date 2024/3/12 14:01
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyBook {
    String name();
    String[] authors();
    double prices();
}


import org.junit.Test;

/**
 * @author Pickle
 * @version V1.0
 * @date 2024/3/12 14:01
 */

public class AnnotationDemo {
    @Test
    public void testAnnotationParse() {
        final Class c = book.class;
        if(c.isAnnotationPresent(MyBook.class)){
            MyBook myBook = (MyBook) c.getDeclaredAnnotation(MyBook.class);
            System.out.println(myBook.name());
            System.out.println(myBook.authors());
            System.out.println(myBook.prices());
        }

    }
}
@MyBook(name = "Java", authors = {"elem " , "Object"},prices = 11.2)
class book{

}
@interface MyBook {
    String name();
    String[] authors();
    double prices();
}
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。