Java 注解学习

来源:互联网 发布:网络事件驱动 编辑:程序博客网 时间:2024/04/28 01:37

1.常见注解

jdk注解

1.@Override 2.@Deprecated 3.@Suppvisewarnings

1.表示方法的复写
2.表示方法已经过时
3.这个仅仅是告诉编译器忽略特定的警告信息,例如在泛型中使用原生数据类型。它的保留策略是SOURCE(译者注:在源文件中有效)并且被编译器丢弃。

第三方注解

2.注解分类

1.源码注解

注解只在源码中存在,编译成class文件就不存在了。

2.编译时注解

在class文件中,还会存在的注解

3.运行时注解

在运行阶段还起作用,甚至会影响运行逻辑的注解

4.元注解

注解的注解

3.自定义注解

1.自定义注解的语法要求

注:注解方法无参无异常
//元注解@Target({ElementType.METHOD,ElementType.TYPE})//target注解作用域@Retention(RetentionPolicy.RUNTIME)//生命周期@Inherited//允许子类继承@Documented//生成javadoc包含注解//使用@interface关键字定义注解public @interface Description {//注解只有一个成员的时候,成员名必须取名为value(),在使用时可以忽略成员名和赋值号(=)String desc();String author();int age() default 18;}

2.使用自定义注解

//使用注解语法://@<注解名>(<成员名1>=<成员值1>,<成员名1>=<成员值1>,...)@Description(desc="I am eyeColor",author="boy",age=18)public String eyeColor(){return "red";}

3.解析注解

1.修改后的注解
//元注解@Target({ElementType.METHOD,ElementType.TYPE})//target注解作用域@Retention(RetentionPolicy.RUNTIME)//生命周期@Inherited//允许子类继承@Documented//生成javadoc生成注解信息//使用@interface关键字定义注解public @interface Description {//注解只有一个成员的时候,成员名必须取名为value(),在使用时可以忽略成员名和赋值号(=)String value();}
2.注解测试类
@Description("i am class annotation")public class test {//使用注解语法://@<注解名>(<成员名1>=<成员值1>,<成员名1>=<成员值1>,...)@Description("i am method annotation")public String eyeColor(){return "red";}}

3.main中解析注解
public static void main(String[] args) {//1.使用类加载器加载类try {Class clazz=Class.forName("test.test");//2.找到类上面的注解boolean isExist=clazz.isAnnotationPresent(Description.class);if(isExist){//3.拿到注解实例Description d=(Description) clazz.getAnnotation(Description.class);System.out.println(d.value());}//4.找到方法上的注解Method[]ms=clazz.getMethods();for(Method m:ms){boolean isMExist=m.isAnnotationPresent(Description.class);if(isMExist){//拿到注解Description d=(Description) m.getAnnotation(Description.class);System.out.println(d.value());}}//另一种解析for(Method m:ms){Annotation[]as=m.getAnnotations();for(Annotation a:as){if(a instanceof Description){System.out.println(((Description) a).value());}}}} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}

注@Inherited只能继承类上面的注解,不能继承接口以及方法注解

当将@Retention(RetentionPolicy.RUNTIME)//生命周期改成Source和class的时候运行时并不能起到作用


0 0
原创粉丝点击