自定义注解
/**
* @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();
}
标签:MyBook,String,import,authors,注解,class
From: https://www.cnblogs.com/poteitoutou/p/18068236