java 注解annotation的使用以及反射如何获取注解
一、注解基本知识
1、元注解
元注解是指注解的注解。包括 @Retention@Target@Document@Inherited四种。
1.Annotation型定义为@interface,所有的Annotation会自动继承java.lang.Annotation这一接口,并且不能再去继承别的类或是接口.
2.参数成员只能用public或默认(default)这两个访问权修饰
3.参数成员只能用基本类型byte,short,char,int,long,float,double,boolean八种基本数据类型和String、Enum、Class、annotations等数据类型,以及这一些类型的数组.
4.要获取类方法和字段的注解信息,必须通过Java的反射技术来获取Annotation对象,因为你除此之外没有别的获取注解对象的方法
5.注解也可以没有定义成员,不过这样注解就没啥用了
自定义注解类时,可以指定目标(类、方法、字段,构造函数等),注解的生命周期(运行时,class文件或者源码中有效),是否将注解包含在javadoc中及是否允许子类继承父类中的注解,具体如下:
1.@Target表示该注解目标,可能的ElemenetType参数包括:
ElemenetType.CONSTRUCTOR构造器声明 ElemenetType.FIELD域声明(包括enum实例) ElemenetType.LOCAL_VARIABLE局部变量声明 ElemenetType.METHOD方法声明 ElemenetType.PACKAGE包声明 ElemenetType.PARAMETER参数声明 ElemenetType.TYPE类,接口(包括注解类型)或enum声明
2.@Retention表示该注解的生命周期,可选的RetentionPolicy参数包括
RetentionPolicy.SOURCE注解将被编译器丢弃 RetentionPolicy.CLASS注解在class文件中可用,但会被VM丢弃 RetentionPolicy.RUNTIMEVM将在运行期也保留注释,因此可以通过反射机制读取注解的信息
3.@Documented指示将此注解包含在javadoc中
4. @Inherited指示允许子类继承父类中的注解
二、在java中如何使用
2.1、定义注解
packagecom.test.annotation;
importjava.lang.annotation.ElementType;
importjava.lang.annotation.Retention;
importjava.lang.annotation.RetentionPolicy;
importjava.lang.annotation.Target;
publicclassMyAnnotation{
/**
*注解类
*@authorT4980D
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public@interfaceMyClassAnnotation{
Stringuri();
Stringdesc();
}
/**
*构造方法注解
*@authorT4980D
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.CONSTRUCTOR)
public@interfaceMyConstructorAnnotation{
Stringuri();
Stringdesc();
}
/**
*我的方法注解
*@authorOwner
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public@interfaceMyMethodAnnotation{
Stringuri();
Stringdesc();
}
/**
*字段注解定义
*@authorOwner
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public@interfaceMyFieldAnnotation{
Stringuri();
Stringdesc();
}
/**
*
*可以同时应用到类上和方法上
*@authorT4980D
*
*/
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public@interfaceYts{
//定义枚举
publicenumYtsType{
util,entity,service,model
}
//设置默认值
publicYtsTypeclassType()defaultYtsType.util;
//数组
int[]arr()default{3,7,5};
Stringcolor()default"blue";
}
}
2.2、基本测试注解
packagecom.test.annotation;
importjava.lang.reflect.Constructor;
importjava.lang.reflect.Field;
importjava.lang.reflect.Method;
importcom.test.annotation.MyAnnotation.MyClassAnnotation;
importcom.test.annotation.MyAnnotation.MyConstructorAnnotation;
importcom.test.annotation.MyAnnotation.MyFieldAnnotation;
importcom.test.annotation.MyAnnotation.MyMethodAnnotation;
importcom.test.annotation.MyAnnotation.Yts;
importcom.test.annotation.MyAnnotation.Yts.YtsType;
@MyClassAnnotation(desc="Theclass",uri="com.test.annotation.Test")
@Yts(classType=YtsType.util)
publicclassTestAnnotation{
@MyFieldAnnotation(desc="Theclassfield",uri="com.test.annotation.Test#id")
privateStringid;
@MyConstructorAnnotation(desc="Theclassconstructor",uri="com.test.annotation.Test#MySample")
publicTestAnnotation(){
}
publicStringgetId(){
returnid;
}
@MyMethodAnnotation(desc="Theclassmethod",uri="com.test.annotation.Test#setId")
publicvoidsetId(Stringid){
System.out.println("methodinfo:"+id);
this.id=id;
}
@MyMethodAnnotation(desc="TheclassmethodsayHello",uri="com.test.annotation.Test#sayHello")
@Yts
publicvoidsayHello(Stringname){
if(name==null||name.equals("")){
System.out.println("helloworld!");
}else{
System.out.println(name+"\t:sayhelloworld!");
}
}
publicstaticvoidmain(String[]args)throwsException{
Class<TestAnnotation>clazz=TestAnnotation.class;
//得到类注解
MyClassAnnotationmyClassAnnotation=clazz.getAnnotation(MyClassAnnotation.class);
System.out.println(myClassAnnotation.desc()+""+myClassAnnotation.uri());
//得到构造方法注解
Constructor<TestAnnotation>cons=clazz.getConstructor(newClass[]{});
MyConstructorAnnotationmyConstructorAnnotation=cons.getAnnotation(MyConstructorAnnotation.class);
System.out.println(myConstructorAnnotation.desc()+""+myConstructorAnnotation.uri());
//获取方法注解
Methodmethod=clazz.getMethod("setId",newClass[]{int.class});
MyMethodAnnotationmyMethodAnnotation=method.getAnnotation(MyMethodAnnotation.class);
System.out.println(myMethodAnnotation.desc()+""+myMethodAnnotation.uri());
//获取字段注解
Fieldfield=clazz.getDeclaredField("id");
MyFieldAnnotationmyFieldAnnotation=field.getAnnotation(MyFieldAnnotation.class);
System.out.println(myFieldAnnotation.desc()+""+myFieldAnnotation.uri());
}
}
2.3、通过反射解析
packagecom.test.annotation;
importjava.lang.reflect.Method;
importjava.util.Arrays;
importcom.test.annotation.MyAnnotation.MyClassAnnotation;
importcom.test.annotation.MyAnnotation.MyMethodAnnotation;
importcom.test.annotation.MyAnnotation.Yts;
importcom.test.annotation.MyAnnotation.Yts.YtsType;
publicclassParseAnnotation{
/**
*解析方法注解
*@param<T>
*@paramclazz
*/
publicstatic<T>voidparseMethod(Class<T>clazz){
try{
Tobj=clazz.newInstance();
for(Methodmethod:clazz.getDeclaredMethods()){
MyMethodAnnotationmethodAnnotation=method.getAnnotation(MyMethodAnnotation.class);
if(methodAnnotation!=null){
//通过反射调用带有此注解的方法
method.invoke(obj,methodAnnotation.uri());
}
Ytsyts=(Yts)method.getAnnotation(Yts.class);
if(yts!=null){
if(YtsType.util.equals(yts.classType())){
System.out.println("thisisautilmethod");
}else{
System.out.println("thisisaothermethod");
}
System.out.println(Arrays.toString(yts.arr()));//打印数组
System.out.println(yts.color());//输出颜色
}
System.out.println("\t\t-----------------------");
}
}catch(Exceptione){
e.printStackTrace();
}
}
/**
*解析类注解
*@param<T>
*@paramclazz
*/
publicstatic<T>voidparseType(Class<T>clazz){
try{
Ytsyts=(Yts)clazz.getAnnotation(Yts.class);
if(yts!=null){
if(YtsType.util.equals(yts.classType())){
System.out.println("thisisautilclass");
}else{
System.out.println("thisisaotherclass");
}
}
MyClassAnnotationclassAnnotation=(MyClassAnnotation)clazz.getAnnotation(MyClassAnnotation.class);
if(classAnnotation!=null){
System.err.println("classinfo:"+classAnnotation.uri());
}
}catch(Exceptione){
e.printStackTrace();
}
}
publicstaticvoidmain(String[]args){
parseMethod(TestAnnotation.class);
parseType(TestAnnotation.class);
}
}
三、注解应用案例
3.1、关于细粒度权限拦截的问题,在Struts2中可以根据登录用户所具有的的权限进行任一一个action方法的拦截,可以定义一个自定义方法注解,例如
@Retention(RetentionPolicy.RUNTIME)//代表Permission注解保留在的阶段
@Target(ElementType.METHOD)//标注在方法上面
public@interfacePermission{
/**模块*/
Stringmodule();
/**权限值*/
Stringprivilege();
}
3、2比如有一个部门action,Department.action,有一个方法publicStringdepartmentlistUI(){}可以这样定义方法
@Permission(module="department",privilege="view")
publicStringdepartmentlistUI(){
}
3.3、然后自定定义一个权限拦截器PrivilegeInterceptor.java并在struts.xml中注册,在实现interceptor接口后,实现方法publicStringintercept(ActionInvocationinvocation)throwsException{},在这里调用任一个action方法都会经过该拦截方法,通过invocation可以获取当前调用的action的名字,以及调用的action的哪个方法,通过这段代码可以获取action名字和方法名。
StringactionName=invocation.getProxy().getActionName();
StringmethodName=invocation.getProxy().getMethod();
System.out.println("拦截到:action的名字:"+actionName+"方法名:"+methodName);
4、然后通过反射技术,获取该方法上的自定义权限注解,获取当前登录的用户(从session中),遍历当前用户的所拥有的权限组,并且遍历任一个权限组下的所有的权限,看是否包括该方法上注解所需的权限。这样就可以完成细粒度的action方法权限拦截了。
privatebooleanvalidate(ActionInvocationinvocation)throwsSecurityException,NoSuchMethodException{
StringmethodName=invocation.getProxy().getMethod();
MethodcurrentMethod=invocation.getAction().getClass().getMethod(methodName);
if(currentMethod!=null&¤tMethod.isAnnotationPresent(Permission.class)){
//得到方法上的注解
Permissionpermission=currentMethod.getAnnotation(Permission.class);
//该方法上的所需要的权限
SystemPrivilegemethodPrivilege=newSystemPrivilege(newSystemPrivilegePK(permission.module(),permission.privilege()));
//得到当前登录的用户
Employeee=(Employee)ActionContext.getContext().getSession().get("loginUser");
//遍历当前用户下的所有的权限组
for(PrivilegeGroupgroup:e.getGroups()){
//如果该权限组下包含,要访问该方法所需要的权限,就放行
if(group.getPrivileges().contains(methodPrivilege)){
returntrue;
}
}
//说明遍历的该用户所有的权限组,没有发现该权限,说明没有该权限
returnfalse;
}
//没有标注注解,表示谁都可以调用该方法
returntrue;
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!