151建议六

91枚举和注解结合使用

1
2
3
4
5
6
7
8
Identifier.java

public interface Identifier {
//无权访问时的礼貌语
String REFUSE_WORD="您无权访问";
//鉴权
public boolean identify();
}

1
2
3
4
5
6
7
8
9
CommonIdentifer.java

public enum CommonIdentifer implements Identifier{
//权限级别
Reader, Author, Admin;
public boolean identify () {
return false;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
Access.java

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Access {
//什么级别可以访问, 默认是管理员
CommonIdentifer level() default CommonIdentifer.Admin;
}

1
2
3
4
5
Foo.java

@Access(level = CommonIdentifer.Admin)
public class Foo {
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Test1.java

public class Test1 {
public static void main (String[] args) {
//初始化商业逻辑
Foo b = new Foo ();
//获取注解
Access access = b.getClass ().getAnnotation (Access.class);
//没有Access注解或者鉴权失败
if (access == null || !access.level ().identify ()) {
//没有Access注解或者鉴权失败System.out.println(access.level() .R
}
}
}