注解解析
package annotation; import org.junit.Test; import java.lang.reflect.Method; import java.util.Arrays; /** * FileName: AnnotationDemo01 * Author: lps * Date: 2022/4/23 13:51 * Sign:刘品水 Q:1944900433 */ public class AnnotationDemo01 { @Test public void parseMethod() throws NoSuchMethodException { //先得到类对象 Class c=BookStore.class; Method m = c.getDeclaredMethod("test"); //判断这个类是否存在这个注解 if (m.isAnnotationPresent(Book.class)){ //获取该注解对象 Book book = (Book) m.getDeclaredAnnotation(Book.class); System.out.println(book.value()); System.out.println(book.price()); System.out.println(Arrays.toString(book.authors())); } } } @Book(value = "《Java学习》",price =188.88,authors = {"刘品水","图书大王"}) class BookStore{ @Book(value = "《迪迦凹凸曼》",price =18.88,authors = {"图书大王"}) public void test(){ } }
package annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * FileName: Book * Author: lps * Date: 2022/4/23 13:51 * Sign:刘品水 Q:1944900433 * @author lps */ @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface Book { String value(); double price() default 100; String[] authors(); }