java @interface 注解类的应用

来源:互联网 发布:青少年犯罪率数据2016 编辑:程序博客网 时间:2024/05/29 19:08

  在项目中,应用拦截器时,使用到了注解类。
  首先创建一个注解类,java中用@interface Annotation{}定义一个注解,@Annotation,一个注解就是一个类。
  注解相当于一种标记,在程序中加上了注解就等于为程序加上了某种标记,以后,JAVAC编译器,开发工具和其他程序可以用反射来了解你的类以及各种元素上有无任何标记,看你有什么标记,就去干相应的事。
  我们项目中主要是通过使用该注解类,实现对页面的拦截效果。
  该类如下:

@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)@Documentedpublic @interface IgnorePermission {}

其中:
  1. 注解@Retention可以用来修饰注解,是注解的注解,称为元注解。
  Retention注解有一个属性value,是RetentionPolicy类型的,Enum RetentionPolicy是一个枚举类型,这个枚举决定了Retention注解应该如何去保持,也可理解为Rentention 搭配 RententionPolicy使用。RetentionPolicy有3个值:CLASS RUNTIME SOURCE
  ①用@Retention(RetentionPolicy.CLASS)修饰的注解,表示注解的信息被保留在class文件(字节码文件)中当程序编译时,但不会被虚拟机读取在运行的时候;
  ②用@Retention(RetentionPolicy.SOURCE )修饰的注解,表示注解的信息会被编译器抛弃,不会留在class文件中,注解的信息只会留在源文件中;
  ③用@Retention(RetentionPolicy.RUNTIME )修饰的注解,表示注解的信息被保留在class文件(字节码文件)中当程序编译时,会被虚拟机保留在运行时

所以他们可以用反射的方式读取。RetentionPolicy.RUNTIME 可以让你从JVM中读取Annotation注解的信息,以便在分析程序的时候使用.

在拦截器中的应用:

public class AdminInterceptor implements HandlerInterceptor {public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {    Profile profile = null;    Object object = request.getSession().getAttribute("org");    if (object instanceof Profile) {        profile = (Profile) object;        return true;    }    HandlerMethod method = (HandlerMethod) handler;    IgnorePermission ssion = method.getMethodAnnotation(IgnorePermission.class);    if (ssion!=null) {        return true;    }else {        response.sendRedirect(RequestUtil.getBasePath(request)+"/home/loginAndreg.do?type=login");        return false;    }        }public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,        ModelAndView modelAndView) throws Exception {    if (null != modelAndView){        modelAndView.addObject("path", RequestUtil.getBasePath(request)+"/resources");        modelAndView.addObject("base", RequestUtil.getBasePath(request));        //个人中心左边菜单栏选中数据        modelAndView.addObject("lm", request.getParameter("lm"));    }}public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)        throws Exception {    }}

补充:java中instanceof的用法

  java 中的instanceof 运算符是用来在运行时指出对象是否是特定类的一个实例。instanceof通过返回一个布尔值来指出,这个对象是否是这个特定类或者是它的子类的一个实例。
  用法:
  result = object instanceof class
  参数:
  Result:布尔类型。
  Object:必选项。任意对象表达式。
  Class:必选项。任意已定义的对象类。
  说明:
  如果 object 是 class 的一个实例,则 instanceof 运算符返回 true。如果 object 不是指定类的一个实例,或者 object 是 null,则返回 false。

原创粉丝点击