---
title: "Java注解简介"
author: "becherpan"
date: "2015-08-28T13:42:37Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2015-08-28T13:42:24Z"
id: 2238658
url: "https://becherpan.iteye.com/blog/2238658"
---

一、作用：

1\. 标记，用于告诉编译器一些信息

2\. 编译时动态处理，如动态生成代码

3\. 运行时动态处理，如得到注解信息

 

二、Annotation 分类

**1、标准 Annotation，Override, Deprecated, SuppressWarnings**

标准 Annotation 是指 Java 自带的几个 Annotation，上面三个分别表示重写函数，不鼓励使用(有更好方式、使用有风险或已不在维护)，忽略某项 Warning

**2、元 Annotation，@Retention, @Target, @Inherited, @Documented**

元 Annotation 是指用来定义 Annotation 的 Annotation，在后面 Annotation 自定义部分会详细介绍含义

**3、自定义 Annotation**

自定义 Annotation 表示自己根据需要定义的 Annotation，定义时需要用到上面的元 Annotation

 

三、自定义注解的示例

 

@Documented  
@Retention(RetentionPolicy.RUNTIME)  
@Target(ElementType.METHOD)  
@Inherited  
public @interface MethodInfo {

    String author() default "AlexPan";

    String date();

    int version() default 1;

}

@Documented 是否会保存到 Javadoc 文档中

@Retention 指示该注解可用的范围，可取值 SOURCE, CLASS, RUNTIME ，SOURCE 大都为 Mark Annotation，这类 Annotation 大都用来校验，比如 Override, SuppressWarnings

@Target 可以用来修饰哪些程序元素，如 TYPE, METHOD, CONSTRUCTOR, FIELD, PARAMETER 等，未标注则表示可修饰所有

@Inherited 是否可以被继承，默认为 false