如何自定义注解:参照@SuppressWarnings定义
一.注解声明为:@interface
二.内部指定成员 通常用value表示
三.可以指定成员的默认值 使用default表示
四.如果自定义注解没有成员 表明是一个标识作用
如果注解有成员 在使用注解时 需要指明成员的值
如果注解有成员 在使用注解时 需要指明成员的值
自定义注解必须配上注解的信息处理流程才有意义
自定义注解通过都会指明两个元注解:Retention target
jdk提供的四种元注解:对现有的注解进行解释说明
Retention:指定所修饰的Annotation的生命周期:SOURCE\CLASS\RUNTIME
只有声明为RUNTIME生命周期的注解 才能通过反射获取
Target:用于指定被修饰的Annotation能用于修饰哪些程序元素
Doctmented:表示所修饰的注解在被javadoc解析时 保留下来
inherited:被它修饰的Annotation具有继承性
通过反射获取注解信息——反射
import org.junit.Test;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedArrayType;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Date;
public class AnnotationTest {
public static void main(String[] args) {
Person p = new Student();
p.walk();
Date date = new Date(2020,10,11);
System.out.println(date);
@SuppressWarnings("unused")
int num = 10;
@SuppressWarnings({"unused","rawtypes"})
ArrayList list = new ArrayList();
}
@Test
public void testGetAnnotation(){
Class clazz = Student.class;
Annotation[] annotations = clazz.getAnnotations();
for (int i = 0;i < annotations.length; i++){
System.out.println(annotations[i]);
}
}
}
@MyAnnotation(value = "hello")
class Person{
private String name;
private int age;
public Person() {
}
@MyAnnotation
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@MyAnnotation
public void walk(){
System.out.println("人走路");
}
public void eat(){
System.out.println("人吃饭");
}
}
interface Info{
void show();
}
class Student extends Person {
@Override
public void walk() {
System.out.println("学生走路");
}
}
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE})
public @interface MyAnnotation {
String value() default "hello";
}