自定义Java注解(annotation)

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

Java从1.5开始引进注解。框架

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

1.看懂别人写的代码,尤为是框架的代码学习

2.能够是本身写的代码简洁清晰spa

 

如今开始学习Java注解了。code

 

1、JDK自带注解blog

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

2. @Deprecated : 过期,使用以后再使用这个方法会有删除线接口

3. @SuppressWarnings : 过滤提示get

 

2、注解分类

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

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

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

 

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. 解析注解

  解析注解须要用到反射,因此在反射里再写吧。

相关文章
相关标签/搜索