java注解

来源:互联网 发布:电脑软件怎么搬家 编辑:程序博客网 时间:2024/06/05 04:56

一个注解是一个类,相当于加一个标记,反射可以加在包、类、方法、成员属性、方法参数、局部变量上。
一、java内置注解类型(三种)
1、@Override
表示当前方法定义覆盖父类中的方法
2、@Deprecated
表示废弃的方法
3、@SuppressWarnings
表示关闭编译器警告信息
例如:@SuppressWarnings(“deprecation”) –禁止废弃警告
二、定义
public @interface myAnnotation{
}
三、元注解
1、定义:注解的注解
2、元注解类型
(1)@Retention(RetentionPolicy.RUNTIME)–保留策略
a)RetentionPolicy.RUNTIME(保留至运行期)–@Deprecated保留策略
b)RetentionPolicy.CLASS(默认值,保留至编译期,class阶段,运行时去掉)
c)RetentionPolicy.SOURCE(保留至源文件,源文件阶段,编译时去掉)–@Override、@SuppressWarnings保留策略
(2)@Target({ElementType.METHOD,ElementType.TYPE})–声明此注解可以添加在哪些位置
四、反射检查注解
示例代码:

package cn.java.demo;public @interface MetaAnnotation {    String value() default "meta-annotation";}

package cn.java.demo;

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

@Retention(value = RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.TYPE })
public @interface MyAnnotation {
// 添加属性,(类似方法,默认是public abstract的)
// 属性值只有value时,在给注解指定属性值时可以省略【value=】
String date() default “2017”;// default设置默认值
String value();
int[] array() default { 3, 2, 1 };
MetaAnnotation annotation() default @MetaAnnotation(“MyAnnotation-me”);
}

package cn.java.demo;@MyAnnotation(value = "value", array = { 1, 2, 3 }, annotation = @MetaAnnotation("AnnotationTest-meta-annotation"))public class AnnotationTest {    @MyAnnotation(value = "value", array = { 1, 2, 3 })    public void print() {        System.out.println("AnnotationTest print...");    }}

package cn.java.demo;

public class AnnotationReflect {

public static void main(String[] args) {    boolean annotationPresent = AnnotationTest.class.isAnnotationPresent(MyAnnotation.class);    if (annotationPresent) {        MyAnnotation myAnnotation = AnnotationTest.class.getAnnotation(MyAnnotation.class);        System.out.println(myAnnotation.date());// 输出注解属性date的值        System.out.println(myAnnotation.array());        System.out.println(myAnnotation.annotation().value());    }}

“`