注解相当于一种标记,在程序中加了注解就等于为程序打上了某种标记,没加,则等于没有某种标记,以后,javac编译器,开发工具和其他程序可以用反射来了解你的类及各种元素上有无何种标记,看你有什么标记,就去干相应的事。标记可以加在包,类,字段,方法,方法的参数以及局部变量上。
常见的注解有:@Deprecated,@Override,@SuppressWarnings
注解其实就是一个特殊的类,他可以有自己的属性;
1.定义一个注解类:
/**
* 自定义一个注解类
*/
@Target(value={ElementType.METHOD,ElementType.TYPE})//表明该注解只能存在类,或者方法上面
@Retention(RetentionPolicy.RUNTIME)//表明该注解在虚拟机运行时仍然纯在;
public @interface MyAnnotation {
//定义了一个color属性,该属性的返回值是String类型;这样使用:@MyAnnotation(color="red");指定了默认值为blue;
String color() default "blue";
//定义了一个value属性,该属性的返回值只能是基本类型加String类型或数组;
//如果没有其他的属性,在定义注解时,可以:@MyAnnotation("haha")
String value();
//该属性的返回值是数组类型;
int[] numbers() default {22,11,32};
}
/**
public enum RetentionPolicy {
SOURCE,//源代码
CLASS,//字节码
RUNTIME//虚拟机运行时;
}
*
*/
2。在需要的地方创建注解类的对象,即@XX;
<span style="font-size:18px;">/**
*定义了一个注解,该注解加在类上,这是一个注解类的对象,可以为其指定属性值;
*/
@MyAnnotation (color= "red",value= "haha",numbers={12,19,15})
public class AnnotationTest {
String str= "";
@MyAnnotation(value ="haha" ,numbers={12,14,15}) //在方法上加注解
public static void main(String[] args) {
//利用反射获取类上的注解对象:该注解是类上的注解!!!
MyAnnotation annotation=AnnotationTest.class .getAnnotation( MyAnnotation.class);
if(annotation!=null){//该类上确实加有注解
System.out.println(annotation.value());//获取属性的值
System.out.println(annotation.numbers()[1]);//获取返回值为数组的属性的值;
}
}
}</span>
3.定义在方法上的注解:以获取数据库连接为例,使用注解替换掉配置文件:
driver=com.mysql.jdbc.Driver |
①定义注解:DbInfo.java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 定义注解,用来演示替代获取数据库连接的配置文件
* @author oterman
*/
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DbInfo {
String driver();
String url();
String user();
String password();
}
②使用注解
public class JdbcUtil {
@DbInfo(driver= "com.mysql.jdbc.Driver",url="jdbc:mysql:///myestore" ,user="root" ,password="root")
public static Connection getConn() throws Exception, NoSuchMethodException{
//在运行的时候,获取注解里各个属性的值;
Class clazz=JdbcUtil.class;
//clazz.getAnnotation(annotationClass);获取类上的注解
//反射获取方法
Method method= clazz.getMethod("getConn", null) ;
//clazz.getField("").getAnnotation(annotationClass);获取字段上的属性
DbInfo annotation = method.getAnnotation(DbInfo .class);//获取方法上的注解
System. out.println(annotation.driver());
System. out.println(annotation.url());
System. out.println(annotation.user());
System. out.println(annotation.password());
return null ;
}
public static void main(String[] args) throws Exception {
getConn();
}
}