您的位置:首页 > 编程语言 > Java开发

Java Annotation Overview

2014-02-20 13:14 288 查看
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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: