Java Annotation Overview

本文详细介绍了Java注解的基本概念、用途以及如何自定义注解和使用元注解。并通过实例展示了如何利用注解替代传统配置文件,并提供了一种在运行时执行连接数据库操作的方法。

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

JAVA注解概述:

1. 注解是给编译器看的,这不同于注释

2. 三个基本的注解:
@Override  告诉编译器这是在覆写方法
@Deprecated 告诉编译器该方法过时了
@SuppressWarnings("unchecked")  不要警告
= (value={"unchecked"})
3. 注解可以用来替代传统的配置文件
4. JDK5 开始,Java增加了对元数据(MetaData)的支持,即Annotation。

自定义注解和反射注解

自定义注解:
1. 新建annotation:(比接口的定义只多了个@符号)
			public @interface myAnnotation {
				//属性
				String who();
				int age();
				String gender();
			}

2. 设置带默认值的注解

			public @interface YouAnnotation {
				String who() default "tom";
				int age() default 0;
				String gender() default "female";
			}

3. 数组情况

			public @interface TheyAnnotation {
				String[] value(); //一定要有()
			}

元Annotation / MetaAnnotation
用来修饰Annotation的。(可以查看@Override的源代码)

@Retention 注解策略,用于指定该Annotation可以保留的域
RetentionPolicy.CLASS 在字节码级别有,在运行级别不可见(默认)
RetentionPolicy.RUNTIME 三个层级均可见,运行时可以反射
RetentionPolicy.SOURCE  只在源码级别上可用,在字节码级别不可见

@Target 指定注解可以被用在哪些范围上
@Documented 写入文档,在使用javadoc命令写入html文档时,该注解一同被写入
@Inherited 可继承性,继承该类的子类依然具有父类该注解的特性

ex.反射注解的方式执行连接数据库操作:

定义注解如下:

			//让一个注解可以在运行时可以被反射
			@Retention(RetentionPolicy.RUNTIME)
			public @interface DbInfo {
				String driver() default "com.mysql.jdbc.Driver";
				String url() default "url = jdbc:mysql://localhost:3306/academic";
				String password() default "1234";
				String username() default "root";
			}

反射注解:

				@DbInfo
				public static Connection getConnection() throws Exception{
					//取得该类的字节码
					Class clazz = Demo2.class;
					//取得该类中名为getConnection()的公共方法
					//参数1:方法名
					//参数2:方法类型参数对应的字节码对象,没有的话,即null
					Method method = clazz.getMethod("getConnection", null);
					//通过该方法,取得该方法上定义的注解
					DbInfo dbInfo = method.getAnnotation(DbInfo.class);
					String driver = dbInfo.driver();
					String url = dbInfo.url();
					String user = dbInfo.username();
					String password = dbInfo.password();
					
					Class.forName(driver);
					return DriverManager.getConnection(url, user, password);
				}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值