java 注解

本文深入讲解Java注解的使用方法,包括元注解@Target、@Retention、@Documented及@Inherited的作用与应用场景,并通过具体示例展示了如何定义自定义注解及如何通过反射获取注解信息。

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

 

import java.lang.annotation.Documented;

import java.lang.annotation.Inherited;

import java.lang.annotation.Retention;

import java.lang.annotation.Target;

import java.lang.annotation.ElementType;

import java.lang.annotation.RetentionPolicy;

 

/*

 * 元注解@Target,@Retention,@Documented,@Inherited

 * 

 *     @Target 表示该注解用于什么地方,可能的 ElemenetType 参数包括:

 *         ElemenetType.CONSTRUCTOR 构造器声明

 *         ElemenetType.FIELD 域声明(包括 enum 实例)

 *         ElemenetType.LOCAL_VARIABLE 局部变量声明

 *         ElemenetType.METHOD 方法声明

 *         ElemenetType.PACKAGE 包声明

 *         ElemenetType.PARAMETER 参数声明

 *         ElemenetType.TYPE 类,接口(包括注解类型)或enum声明

 *         

 *     @Retention 表示在什么级别保存该注解信息。可选的 RetentionPolicy 参数包括:

 *         RetentionPolicy.SOURCE 注解将被编译器丢弃

 *         RetentionPolicy.CLASS 注解在class文件中可用,但会被VM丢弃

 *         RetentionPolicy.RUNTIME VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息。

 *         

 *     @Documented 将此注解包含在 javadoc 中

 *     

 *     @Inherited 允许子类继承父类中的注解

 *   

 */

@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

@Documented

@Inherited

/*

 * 定义注解 Test

 * 注解中含有两个元素 id 和 description

 * description 元素 有默认值 "no description"

 */

public @interface Test{

public int id();

public String description() default "no description";

}

---------------------------------------------------------------------------------------------------------------

import java.lang.reflect.Method;

 

public class Test_1 {

public void mthd(){

}

/*

* 被注解的三个方法

*/

@Test(id = 1, description = "hello method_1")

public void method_1() {

}

 

@Test(id = 2)

public void method_2() {

}

 

@Test(id = 3, description = "last method")

public void method_3() {

}

 

/*

* 解析注解,将Test_1类 所有被注解方法 的信息打印出来

*/

public static void main(String[] args) {

Method[] methods = Test_1.class.getDeclaredMethods();

for (Method method : methods) {

/*

* 判断方法中是否有指定注解类型的注解

*/

boolean hasAnnotation = method.isAnnotationPresent(Test.class);

if (hasAnnotation) {

/*

* 根据注解类型返回方法的指定类型注解

*/

Test annotation = method.getAnnotation(Test.class);

System.out.println("Test( method = " + method.getName()

+ " , id = " + annotation.id() + " , description = "

+ annotation.description() + " )");

System.out.println(annotation.annotationType());

}

}

}

 

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值