注解在Java中应用很广泛,在各种框架中都有,像spring,hibernate,myBatis等等。注解是在java1.5引入的,相当于是一种元数据,可以使用注解解析工具或编译器对其进行解析,也可以指定注解在编译期或运行期有效。
1.创建自定义注解
package com.lg.aop.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 注解前面有4中元注解: 分别是:@Documented、@Target、@Inherited 、@Retention
* 1.@Documented:表示使用该注解的元素应被javadoc或类似工具文档化
* 2.@Target :支持注解的元素的种类TYPE, METHOD, CONSTRUCTOR, FIELD
* 3.@Inherited:表示一个注解类型会被自动继承
* 4.@Retention:表示注解类型保留时间的长短,RetentionPolicy参数值有SOURCE, CLASS, 以及RUNTIME。
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Role {
public abstract String name() default "";
}
ElementType枚举:
package java.lang.annotation;
/**
* A program element type. The constants of this enumerated type
* provide a simple classification of the declared elements in a
* Java program.
*
* <p>These constants are used with the {@link Target} meta-annotation type
* to specify where it is legal to use an annotation type.
*
* @author Joshua Bloch
* @since 1.5
*/
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE,
/** Field declaration (includes enum constants) */
FIELD,
/** Method declaration */
METHOD,
/** Parameter declaration */
PARAMETER,
/** Constructor declaration */
CONSTRUCTOR,
/** Local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
PACKAGE
}
RetentionPolicy枚举类
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE,
/**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.
*/
CLASS,
/**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}
注意点:
- 注解方法不能有参数
- 注解方法的返回类型只能是原始类型,字符串,枚举,注解,或以上类型构成的数组。
- 注解方法可以包含默认值。
2.注解的解析
注解的解析使用反射机制进行解析,请注意注解保持性策略应该是RUNTIME,否则它的信息在运行期无效。
package com.lg.aop.annotation;
import java.lang.reflect.Method;
public class RoleParse {
public static String roleParse(Class target,String methodName) throws NoSuchMethodException, SecurityException {
String roleName="";
Method method=target.getMethod(methodName);
//判断是否有Role注解
if(method.isAnnotationPresent(Role.class)) {
//获取注解
Role role=method.getAnnotation(Role.class);
//获取注解方法值
roleName=role.name();
}
return roleName;
}
}