第二十一:Java Annotation(中)

本文深入探讨了Java注解的定义、作用及其与反射的结合应用,包括注解的继承、保留策略、注解的获取与使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.

我们定义的所有annotation都继承于java.lang.annotation.Annotation接口

二.

如果我们通过手工的方式来声明一个接口,让该接口继承Annotation接口,

那么我们定义的这个接口仅仅是一个普通的接口而已,与注解没有任何关系
public interface I extends Annotation......仅仅是定义一个接口,而不是注解

三.

java.lang.annotation.Annotation就是一个接口,它本身并不是注解

四.

介绍:Retention及RetentionPolicy与反射的结合在Annotation中的应用

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

@Retention(RetentionPolicy.RUNTIME)//编译程序将Annotation存储于class文件中,可由VM读取
public @interface MyAnnotation {
	String hello();
	String world();
}

public class MyTest {
	
	@MyAnnotation(hello="beijing",world="shanghai")
	@Deprecated
	@SuppressWarnings("unchecked")
	public void output(){
		System.out.println("output something");
	}
	
}

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

public class MyReflection {
	public static void main(String[] args) throws Exception {
		MyTest myTest = new MyTest();

		Class<MyTest> c = MyTest.class;

		Method method = c.getMethod("output", new Class[] {});

		if (method.isAnnotationPresent(MyAnnotation.class)) {// 判断此注解是否存在此元素(方法)上
			method.invoke(myTest, new Object[] {});// 执行指定对象上的方法
			// 获取指定元素(方法)上注解(返回指定的注解或者返回null)
			MyAnnotation myAnnotation = method
					.getAnnotation(MyAnnotation.class);

			String hello = myAnnotation.hello();// 获取注解的属性值
			String world = myAnnotation.world();

			System.out.println(hello);
			System.out.println(world);
		}
		Annotation[] annotations = method.getAnnotations();// 返回此元素上所有的注解
		for (Annotation annotation : annotations) {
			// 返回此注解的注解类型
			System.out.println(annotation.annotationType().getName());
		}
	}
}


五.

Class Constructor Field Method Package等类别,都实现了AnnotatedElement接口


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值