//定义annotation运行的环境
@Retention(RetentionPolicy.RUNTIME)
//定义annotation的类型
@Target(ElementType.TYPE)
public @interface myAnnotation {
String name() default "张三";
String[] sex() default {};
WeekDay weekDay() default WeekDay.Monday;
}
操作annotation
@myAnnotation(name="XXX",sex={"男","女","人妖"},weekDay=WeekDay.Friday)
public class AnnotationDemo {
public static void main(String[] args) {
Date date = new Date();
}
@Override
public String toString() {
return "AnnotationDemo [getClass()=" + getClass() + ", hashCode()="
+ hashCode() + ", toString()=" + super.toString() + "]";
}
}
class MyAnnotationDemo{
public static void main(String[] args) {
Class<AnnotationDemo> annotationDemo = AnnotationDemo.class;
Annotation[] annotation = annotationDemo.getAnnotations();
for (Annotation annotation2 : annotation) {
if (annotation2 instanceof myAnnotation) {
System.out.println("我的注解找到了、、、、、、、、");
}
}
if (annotationDemo.isAnnotationPresent(myAnnotation.class)) {
myAnnotation annotation1 = annotationDemo.getAnnotation(myAnnotation.class);
System.out.println(annotation1.name());
System.out.println(Arrays.toString(annotation1.sex()));
System.out.println(annotation1.weekDay());
// System.out.println();
}
}
}
07-28
07-28
07-28