每一个注解都是一个类。使用注解相当于创建其实例对象。
@Deprecated:过时注解。
@Override:是否覆盖父类方法。
注解类:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)//生命周期
@Target({ElementType.METHOD,ElementType.TYPE})//可以放置的位置。
public @interface ItcastAnnotation {
}
import java.lang.annotation.Annotation;
@ItcastAnnotation
public class AnnotationTest {
public static void main(String[] args) {
if(AnnotationTest.class.isAnnotationPresent(ItcastAnnotation.class)){
Annotation anno=AnnotationTest.class.getAnnotation(ItcastAnnotation.class);
System.out.println(anno);
}
}
}
@Retention为元注解:有三种取值,
RetentionPolicy.SOURCE,
RetentionPolicy.CLASS,
RetentionPolicy.RUNTIME,分别对应java源文件,class文件,内存中字节码。默认是在class阶段。
@Target:指定这个注解可以放在什么位置上,可以定义参数数组的方式指定多个参数;详细参阅Enum ElementType
为注解增加属性:
为注解增加属性:
import java.lang.annotation.Annotation;
@ItcastAnnotation(color="bule",value=3)
public class AnnotationTest {
public static void main(String[] args) {
if(AnnotationTest.class.isAnnotationPresent(ItcastAnnotation.class)){
ItcastAnnotation anno=(ItcastAnnotation)AnnotationTest.class.getAnnotation(ItcastAnnotation.class);
System.out.println(anno);
System.out.println(anno.color());
//System.out.println(anno.lamp().nextLamp());
System.out.println(anno.annotation().name());
}
}
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)//生命周期
@Target({ElementType.METHOD,ElementType.TYPE})//可以放置的位置。
public @interface ItcastAnnotation {
String color();
int[] value();
LampText.Lamp lamp() default LampText.Lamp.RED;
meAnnotation annotation() default @meAnnotation(name="XXX");
}
public @interface meAnnotation {
String name();
}
如果注解中只有一个属性需要设置值。那么可以不写属性名。直接写值,@IAnnotation("red");
默认赋值可以被覆盖。在使用时可以重新赋值。
注解的返回类型可以是基本类型,String,class。注解类型,枚举,数组。还可以是前面这些类型的数组