您的位置:首页 > 编程语言 > Java开发

java注解的简单了解基础知识

2020-04-21 21:10 302 查看

注解

@Override 重写父类的方法
@Deprecated 声明方法过时
@Suppvisewarnings 忽略警告
忽略过时警告
@Suppvisewarnings(“deprecation”)

注解分类

按照运行机制分

1.源码注解 class文件看不到,在源码看得到 2.编译时注解 在class文件,源码依旧看的到 3.运行时注解 在运行阶段还起作用,甚至会影响运行逻辑的注解

自定义注解

  • 使用 @interface 关键字定义注解
  • 成员以 无形参 无异常(不能抛出异常) 的形式声明
  • 可以用default 关键字 声明一个默认值
  • 成员类型受限 , 合法的类型包括 基本数据类型 及 String,Class,Annotation,Enumeration
  • 如果注解只有一个成员,则成员名必须取名为 value(),在使用时可以忽略成员名和赋值号(=)
  • 注解可以没有成员 没有成员的注解称为标识注解

例子

``
public @interface Description {

String desc();

String author();

int age() default 20;

}

``

元注解

``
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Description {

String desc();

String author();

int age() default 20;

}

``

元注解解释

@Target({ElementType.METHOD,ElementType.TYPE})
Target 作用域 ElementType.METHOD 方法声明
ElementType.TPYE 类,接口声明
ElementType.CONSTRUCTOR 构造方法声明
ElementType.FIELD 字段声明 成员变量
ElementType.LOCAL_VARIABLE 局部变量声明
ElementType.PACKAGE 包声明
ElementType.PARMENTER 参数声明
@Retention(RetentionPolicy.RUNTIME)
Retention 生命周期 RententionPolicy.RUNTIME 运行时存在,可以通过反射读取
RententionPolicy.CLASS 编译时会记录到class中,运行时忽略
RententionPolicy.SOURCE 只有在源码显示,编译时会丢弃

Class c = Class.forName("类路径"); boolean isExist = c.isAnnotationPresent(注解类名.class); if(isExist){ 	注解类名 d = (注解类名)c.getAnnotation(注解类名.class); 	System.out.println(d.value()); 	}

@Inherited
允许子类继承 (继承类的注解 不会继承方法的注解 , 但是接口实现是不会继承的)
@Documented
生成javadoc时会包含注解

  • 点赞
  • 收藏
  • 分享
  • 文章举报
.树懒. 发布了16 篇原创文章 · 获赞 2 · 访问量 202 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: