- 定义权限验证注解:
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.METHOD)
public @interface NeedPermission {
}
- 编写包含注解的方法:
public class Service {
@NeedPermission
public void doSomething() {
System.out.println("执行需要权限验证的操作");
}
}
- 使用反射获取注解信息并判断:
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws NoSuchMethodException {
Service service = new Service();
Method method = service.getClass().getMethod("doSomething");
if (method.isAnnotationPresent(NeedPermission.class)) {
System.out.println("该方法需要进行权限验证");
} else {
System.out.println("该方法不需要进行权限验证");
}
}
}