简体   繁体   English

Java自定义注释

[英]Java custom annotation

I want to write custome annonation on method .my usecase is - I have user which has role so when user try to access some method of class then i want to check his roles. 我想在方法上写自定义注释。我的用例是-我有一个具有角色的用户,因此当用户尝试访问某个类的方法时,我想检查他的角色。 so roles i want pass in annotation. 所以我想传递注释中的角色。

my code is here package com.samples; 我的代码在这里com.samples包中;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Roles {

public String roles();
}


package com.samples;

public class AnnotationExample {

@Roles(roles="admin")
public void createAction(){
String userrole = "admin"; // this hardcoded value
            // a
// here i want to compare annotaiton value with user role


}
}

How can i do this ? 我怎样才能做到这一点 ? It is possible to declare annotation value as object value. 可以将注释值声明为对象值。 like @Roles(Role.AADMIN) 像@Roles(Role.AADMIN)

To check the annotations you need to use reflection. 要检查注释,您需要使用反射。

Roles r = AnnotationExample.class.getMethod("createAction").getAnnotation(Roles.class);
if ("admin".equals(r.roles())) //has admin roles

It is possible to declare annotation value as object value. 可以将注释值声明为对象值。 like @Roles(Role.AADMIN) 像@Roles(Role.AADMIN)

I think what you want is a Enum. 我想您想要的是一个枚举。

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Roles {

   public Role roles();
}

enum Role { ADMIN, USER };

public class AnnotationExample {

   @Roles(roles=Role.ADMIN)
   public void createAction(){
      Role userrole = Role.ADMIN;
    }
}

If you really need to reinvent security annotations (if you don't want to use already available options with declarative security like EJB or Spring) you may at least want to see how they implement it. 如果您确实需要重新设计安全性注释(如果您不想使用具有声明性安全性的现有选项,例如EJB或Spring),那么您可能至少想看看它们是如何实现的。 Here for example for one of EJB implementations. 这里以EJB实现之一为例。

But maybe you would reconsider? 但是也许您会重新考虑?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM