jdk1.5版本新增注解、泛型、并发包(并发编程),即在jdk1.5以上版本才可以使用注解。
注解的分类:
一、.jdk内置注解
常见注解:
(1) @SuppressWarnings 再程序前面加上可以在javac编译中去除警告--阶段是SOURCE。如:
@SuppressWarnings("all")
(2) @Deprecated 带有标记的包,方法,字段说明其过时----阶段是SOURCE
(3)@Overricle 打上这个标记说明该方法是将父类的方法重写--阶段是SOURCE
二、自定义注解
1.@Target、@Retention
* 定义注解使用@interface
* @Target 表示允许在哪里使用的范围
* @Retention 表示允许反射获取信息
简单的示例:
@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationTest {
}
class Test{
private String S;
Test(String s) {
S = s;
}
@AnnotationTest
public void add(){
}
}
自定义注解的写法示例:
package com.wang.annotation;
import javax.xml.bind.Element;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/*
* 自定义注解
* 定义注解使用@interface
* @Target 表示允许在哪里使用的范围
* @Retention 表示允许反射获取信息
* */
@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationTest {
//传入参数
String name() default "";
int id() default 0;
String[] arr() ;
}
class Test{
private String S;
@AnnotationTest(name = "value",id=8,arr={"12","ddf"})
public void add(){
}
}
2.@Documented
@Documented 注解表明这个注解应该被 javadoc工具记录. 默认情况下,javadoc是不包括注解的. 但如果声明注解时指定了 @Documented,则它会被 javadoc 之类的工具处理, 所以注解类型信息也会被包括在生成的文档中,是一个标记注解,没有成员。 示例:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.stereotype;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {
String value() default "";
}
3. @Inherited
@Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。