Java Annotation Overview详解
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);
}
上一篇:解析Java和Eclipse中加载本地库(.dll文件)的详细说明
栏 目:JAVA代码
本文标题:Java Annotation Overview详解
本文地址:http://www.codeinn.net/misctech/120660.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




