元注解
首先Java提供了4个元注解来定义其他注解
@Target用来定义注解将应用于什么地方(如一个方法或者一个域)
@Retention用来定义注解在哪一个级别可用,在源代码中(source),类文件中(class)或者运行时(runtime)
@Documented用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。
@Inherited 允许子类继承父类的注解
自定义注解小例子
假如我们在一个需要登录权限控制的系统里,需要定义一个注解,@needLogin,当定义注解后,说明这个方法必须要登录才能访问,否则,跳转到登陆页面。代码如下
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface NeedLogin {
}
public class BlogController {
@NeedLogin
public String myBlog() {
return "myBlog";
}
public String index() {
return "index";
}
}
public class Test {
public static void main(String[] args) {
try {
Class clazz = Class.forName("cn.learn.annotation.BlogController");
Method[] methods = clazz.getMethods();
for (Method method : methods) {
NeedLogin needLogin = method.getAnnotation(NeedLogin.class);
if (needLogin != null) {
System.out.println("needLogin:" + method.getName());
continue;
}
System.out.println("pass:" + method.getName());
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
但在实际中这种权限控制,可以用拦截器或过滤器。或其他权限工具。
其他类似参考
http://www.jasongj.com/2016/01/17/Java1_%E6%B3%A8%E8%A7%A3Annotation/