自定义Java注解(annotation)

https://www.imooc.com/learn/456  笔记

Java从1.5开始引进注解。

首先解决一个问题,为什么要学习Java注解?

1.看懂别人写的代码,尤其是框架的代码

2.可以是自己写的代码简洁清晰

 

现在开始学习Java注解了。

 

一、JDK自带注解

1. @Override : 覆盖,继承父类、实现接口重写方法时使用

2. @Deprecated : 过时,使用之后再使用这个方法会有删除线

3. @SuppressWarnings : 过滤提示

 

二、注解分类

1. 根据运行机制分: 源码注解、编译时注解、运行时注解

2. 根据来源分: JDK注解、第三方注解、自定义注解

3. 元注解 : 注解的注解,自定义注解时使用

 

三、自定义注解

1. 语法要求

  a. 使用 @interface 定义

  b. 成员以无参无异常的方式声明

  c. 可以使用default为成员设置默认值

  d. 成员类型包括 基本数据类型,String,Class,Annotation,Enumeration

  e. 只有一个成员时,名称必须为value,使用时可以忽略=

  f. 注解类可以没有成员,称为标识注解

  代码示例  

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Customize {
    String value() default "I am annotation";
}

 2. 注解的使用

  @注解名(<成员名1>=<成员值1>,<成员名2>=<成员值2>,<成员名3>=<成员值3>,......)

3. 解析注解

  解析注解需要用到反射,所以在反射里再写吧。

posted @ 2018-12-23 17:58  aston  阅读(179)  评论(0编辑  收藏  举报