当前位置: 移动技术网 > IT编程>开发语言>Java > Java Annotation Overview详解

Java Annotation Overview详解

2019年07月22日  | 移动技术网IT编程  | 我要评论

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); 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网