元注解了解

除了直接使用JDK 定义好的注解,我们还可以自定义注解,在JDK 1.5中提供了4个标准的用来对注解类型进行注解的注解类,我们称之为 meta-annotation(元注解),他们分别是:

@Target注解

@Retention注解

@Documented注解

@Inherited注解

1、@Target注解
Target注解的作用是:描述注解的使用范围(即:被修饰的注解可以用在什么地方) 。

Target注解用来说明那些被它所注解的注解类可修饰的对象范围:注解可以用于修饰 packages、types(类、接口、枚举、注解类)、类成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数),在定义注解类时使用了@Target 能够更加清晰的知道它能够被用来修饰哪些对象,它的取值范围定义在ElementType 枚举中。

2、@Retention注解
Reteniton注解的作用是:描述注解保留的时间范围(即:被描述的注解在它所修饰的类中可以被保留到何时) 。

Reteniton注解用来限定那些被它所注解的注解类在注解到其他类上以后,可被保留到何时,一共有三种策略,定义在RetentionPolicy枚举中。

3、@Documented注解
Documented注解的作用是:描述在使用 javadoc 工具为类生成帮助文档时是否要保留其注解信息。

为了验证Documented注解的作用到底是什么,我们创建一个带有 @Documented 的自定义注解类。

4、@Inherited注解
Inherited注解的作用是:使被它修饰的注解具有继承性(如果某个类使用了被@Inherited修饰的注解,则其子类将自动具有该注解)。

注解应用举例

首先自定义一个注解类。

package com.pengjunlee;

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
public @interface MyAnnotation {

public String name() default "pengjunlee";

}
在 AnnotationTest 中使用反射获取注解信息。

package com.pengjunlee;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

@MyAnnotation(name = “name of type”)
public class AnnotationTest {

@MyAnnotation(name = "name of method")
public String hello() {
	return "hello";
}

public static void main(String[] args) throws NoSuchMethodException, SecurityException {

	Class<AnnotationTest> annotationTest = AnnotationTest.class;
	// 获取类上的所有注解
	Annotation[] annotations = annotationTest.getAnnotations();
	for (Annotation annotation : annotations) {
		// 获取注解的全类名
		System.out.println(annotation.annotationType().getName());
	}

	// 获取 hello() 方法
	Method method = annotationTest.getMethod("hello", new Class[] {});

	// hello() 方法上是否有 MyAnnotation 注解
	if (method.isAnnotationPresent(MyAnnotation.class)) {

		// 获得注解
		MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);

		// 获取注解的内容
		System.out.println(annotation.name());

	}
}

}
运行程序,打印结果如下:

com.pengjunlee.MyAnnotation
name of method

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值