1、元注解
元注解是指注解的注解。包括 @Retention @Target @Document @Inherited四种。
1.1、@Retention: 定义注解的保留策略
@Retention(RetentionPolicy.SOURCE) //注解仅存在于源码中,在class字节码文件中不包含
@Retention(RetentionPolicy.CLASS) // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
@Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到
1.2、@Target:定义注解的作用目标
@Target(ElementType.TYPE) //接口、类、枚举、注解
@Target(ElementType.FIELD) //字段、枚举的常量
@Target(ElementType.METHOD) //方法
@Target(ElementType.PARAMETER) //方法参数
@Target(ElementType.CONSTRUCTOR) //构造函数
@Target(ElementType.LOCAL_VARIABLE)//局部变量
@Target(ElementType.ANNOTATION_TYPE)//注解
@Target(ElementType.PACKAGE) ///包
1.3、@Document:说明该注解将被包含在javadoc中
1.4、@Inherited:说明子类可以继承父类中的该注解
2、java 注解的自定义
定义新的Annotation类型使用@interface关键字(在原有的interface关键字前增加@符号)
public@interface Test{
}
定义了该Annotationz之后,就可以在程序的任意地方使用Annotation
@test
publlicclassMyClass
{
}
只有当定义Annotation使用了 @Retention(RetentionPolicy.RUNTIME)修饰时,该Annotation才会在运行时可见
下面是自定义注解的一个例子
@Documented
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)public@interface Yts {public enumYtsType{util,entity,service,model}public YtsType classType() defaultYtsType.util;
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inheritedpublic@interface HelloWorld {public String name()default "";
}
@Retention(RetentionPolicy.RUNTIME)
定义的这个注解是注解会在class字节码文件中存在,在运行时可以通过反射获取到。
@Target({ElementType.TYPE,ElementType.METHOD})
因此这个注解可以是类注解,也可以是方法的注解
这样一个注解就自定义好了,当然注解里面的成员可以为基本的数据类型,也可以为数据,Object等等
3 注解是定义好了,那么怎么来得到,解析注解呢?
java的反射机制可以帮助,得到注解,代码如下:
[java] view plain copypublic classParseAnnotation {public voidparseMethod(Class clazz) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException, InstantiationException{
Object obj= clazz.getConstructor(new Class[]{}).newInstance(newObject[]{});for(Method method : clazz.getDeclaredMethods()){
HelloWorld say= method.getAnnotation(HelloWorld.class);
String name= "";if(say != null){
name=say.name();
method.invoke(obj, name);
}
Yts yts= (Yts)method.getAnnotation(Yts.class);if(yts != null){if(YtsType.util.equals(yts.classType())){
System.out.println("this is a util method");
}else{
System.out.println("this is a other method");
}
}
}
}
@SuppressWarnings("unchecked")public voidparseType(Class clazz) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException{
Yts yts= (Yts) clazz.getAnnotation(Yts.class);if(yts != null){if(YtsType.util.equals(yts.classType())){
System.out.println("this is a util class");
}else{
System.out.println("this is a other class");
}
}
}
}
在spring mvc中声明
@Component, @Service, @Controller or @Repository就相当于声明了一个bean