---
title: "annotation基础"
author: "dingjun1"
date: "2008-08-04T17:09:07Z"
tags: []
slug: "annotation"
draft: false
lastmod: "2008-08-04T17:09:07Z"
id: 223930
url: "https://dingjun1.iteye.com/blog/223930"
---

Annotation整理
1、	基础
annotation可以从源文件、class文件或者以在运行时反射的多种方式被读取。
Annotation类型声明于一般的接口声明极为类似，区别只在于它在interface关键字前面使用"@"符号。

annotation类型的每个方法声明定义了一个annotation类型成员，但方法声明不必有参数或 者异常声明；方法返回值的类型被限制在以下的范围：primitives、String、Class、enums、annotation和前面类型的数 组（不能为void ）；方法可以有默认值。
示例：
自定义一个annotation类型

```java

public @interface LearnAnnotation {
		public String name();
		String date() default "2008-9-1";
		int id();
}

```

使用annotation:

```java

@LearnAnnotation(name=”method name:buy”,date=”2008-8-15”,id=3)
public void buy(String customer){
		System.out.println(“…”);
}

	@LearnAnnotation(name="sort",date="2008-8-4",id=0)

	@LearnAnnotation(name="print",id=5)

```


有默认值的成员可以在使用时不列出，成员的值必须在编译时可以转化为常量

如果只有一个参数，可以不写成员名称，直接写值

```java

public @interface Copyright{
	public String value();
}
@Copyright("2002 Yoyodyne Propulsion Systems")

import java.lang.annotation.*; 
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface Test { }

```

2、