如何扩展Java注释? [英] How to extend Java annotation?

查看:206
本文介绍了如何扩展Java注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在项目中,我使用pre定义的注释 @With

  @With(Secure.class)
公共类的测试{// ....

的源$ C ​​$ C @With

  @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
公共@interface随着{    类<> []值()默认{};
}

我要编写自定义批注 @Secure ,它会自动将 Secure.class @With 注释。那怎么办?


如果我做的这样吗?将它的工作?

  @With(Secure.class)
@Target({} ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
公共@interface安全{}


解决方案

从Java语言规范,的第9.6节注释类型的:


  

没有extends子句是允许的。 (译注类型都隐延长 annotation.Annotation


所以,你不能扩展的一种诠释。你需要使用一些其他机制或创建一个code的识别和处理自己的注释。 Spring允许你组其他Spring的注解在自己的自定义注释。但仍然没有延长。

In my project I use pre-defined annotation @With:

@With(Secure.class)
public class Test { //....

The source code of @With:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface With { 

    Class<?>[] value() default {};
}

I want to write custom annotation @Secure, which will automatically place Secure.class to @With annotation. How to do that?


What if I do like this? Will it work?

@With(Secure.class)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Secure {

}

解决方案

From Java language specification, Chapter 9.6 Annotation Types:

No extends clause is permitted. (Annotation types implicitly extend annotation.Annotation.)

So, you can not extend an Annotation. you need to use some other mechanism or create a code that recognize and process your own annotation. Spring allows you to group other Spring's annotation in your own custom annotations. but still, no extending.

这篇关于如何扩展Java注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆