@Rentention:用于指定该Annotation可以保留的域,@Rentention包含一个RententionPolicy类型的属性,通过这个属性指定域: RententionPolicy.CLASS:编译器将把注解记录在Class文件中,当运行java程序时,jvm不会保留注解。这是默认值。 RententionPolicy.RUNTIME:编译器将把注解记录在文件中,当运行java程序时,jvm会保留注解。 RententionPolicy.SOURCE:编译器直接丢弃这种策略的注解。 注:RententionPolicy.RUNTIME是我们最常用的值。 @Target:指定注解用于修饰注解的哪些成员。属性值是枚举类型ElementType中的某些值。 @Documented:用于指定被该Annotation修饰的Annotation类将被javadoc工具提取成文档。 @Inherited:被它修饰的Annotation将具有继承性,如果某个类使用了被@Inherited修饰的Annotation,则其子类将自动具有该注解。
注解声明
package cn.edu.chd.annotation;
/**
* @author Rowand jj
*
*这是一个注解的示例
*
*
*1.注解接收的类型有:
*String类型,基本数据类型,Class类型,枚举类型,注解类型,以及以上类型的一维数组
*其他类型不可以,比如List list();//这是错误的
*
*2.如果一个属性的名字为value,则调用该注解时可以不指定名字:
*public @interface annotation
*{
* String value();
*}
* 此时,@demo("zhangsan")等价于@demo(value="zhansgan")
*
*/
public @interface MyAnnotation
{
String name();//为这个注解添加了一个名为name的属性
String password() default "123";//配置缺省值
int age() default 13;
Gender gender() default Gender.FEMAIL;//枚举类型,并有默认值
Class clazz();//一个类类型
MyAnnotation2 my2();//注解中嵌套注解
int[] arr() default {1,23,4};//数组
}
使用注解:
@MyAnnotation(name="zhansgan",age=33,clazz=MyAnnotationDemo.class,my2=@MyAnnotation2(like="chifan"))
public void aa()
{
}
package cn.edu.chd.annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * @author Rowand jj * *保存连接数据库参数的注解 * *@Retention(RetentionPolicy.RUNTIME)这是指定当前注解的作用域是运行时 */ @Retention(RetentionPolicy.RUNTIME) public @interface DBInfo { String url() default "jdbc:mysql://localhost:3306/db_test"; String username() default "root"; String password() default "root"; }
package cn.edu.chd.annotation;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCUtils
{
@DBInfo(password="sjjhong")
public static Connection getConnection(String url,String username,String password)
throws SQLException
{
return DriverManager.getConnection(url, username, password);
}
/**
* 通过反射技术获取方法上注解的信息
*/
public static void main(String[] args) throws Exception
{
Method method = JDBCUtils.class.getMethod("getConnection", String.class,String.class,String.class);
DBInfo info = method.getAnnotation(DBInfo.class);
String url = info.url();
String password = info.password();
String username = info.username();
// 调用方法
System.out.println(method.invoke(null,url,username,password));
}
}
控制台输出:com.mysql.jdbc.JDBC4Connection@3bcd288e 成功获取到了参数. 应用场景二:通过注解技术注入对象
package cn.edu.chd.annotation2;
public class Person
{
private String name;
private int age;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.a