1 JDK自带注解
1.1 @Override:方法重写
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
1.2 @Deprecated:过时的方法
@Documented
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, MODULE, PARAMETER, TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Deprecated {
}
@SuppressWarnings(value={"deprecation"}) 关键字用途
deprecation 使用了不赞成使用的类或方法时的警告
unchecked 执行了未检查的转换时的警告,例如当使用集合时没有用泛型 (Generics) 来指定集合保存的类型。
fallthrough 当 Switch 程序块直接通往下一种情况而没有 Break 时的警告。
path 在类路径、源文件路径等中有不存在的路径时的警告。
serial 当在可序列化的类上缺少 serialVersionUID 定义时的警告。
finally 任何 finally 子句不能正常完成时的警告。
all 关于以上所有情况的警告。
1.3 @Suppvisewarnings:去掉警告
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, MODULE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
}
2 注解的分类
2.1 按照运行机制分
源码注解:@Retention(RetentionPolicy.SOURCE)
编译时注解:@Retention(RetentionPolicy.CLASS)
运行时注解:@Retention(RetentionPolicy.RUNTIME)
2.2 按照来源分
来自JDK的注解
来自第三方的注解:Spring、Mybatis
我们自己定义的注解
2.3 元注解
@interface关键字定义注解
成员以无参数无异常方式声明
可以用default为成员指定一个默认值
3 解析注解
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited//不能接口继承注解,并且继承类的时候,只会继承类的注解,不会继承方法的注解
@Documented
public @interface Description {
String value() default "";
}
@Description("I am super class")
public class Person {
@Description("I am super class method")
public String name(){
return null;
}
public int age(){
return 0;
}
public void sing(){
}
}
//@Description("I am class annotation")
public class Child extends Person {
//@Description("I am method annotation")
public String name() {
return null;
}
public int age() {
return 0;
}
public void sing() {
}
}
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class ParseAnn {
public static void main(String[] args) {
Class clazz = Child.class;
boolean isExist = clazz.isAnnotationPresent(Description.class);
if(isExist){
Description description = (Description) clazz.getAnnotation(Description.class);
System.out.println("Description Class "+description.value());
}
/**
* 找到方法上的注解
*/
Method[] methods = clazz.getMethods();
for(Method method:methods){
boolean isMExist = method.isAnnotationPresent(Description.class);
if (isMExist){
Description description = (Description) method.getAnnotation(Description.class);
System.out.println("Description method1 "+description.value());
}
}
/**
* 找到Description注解
*/
for(Method method:methods){
Annotation[] annotations = method.getAnnotations();
for(Annotation annotation:annotations){
if (annotation instanceof Description){
System.out.println("Description method2 "+((Description) annotation).value());
}
}
}
}
}