简体   繁体   English

修改自定义注释的参数值

[英]Modify parameter value of custom annotation

Is there any way to implement annotation in order to change his parameter value by itself? 有什么方法可以实现注释以自行更改其参数值?

For example: 例如:

I would like create custom RequestMapping annotation to get rid of some code duplicates. 我想创建自定义RequestMapping注释,以消除一些重复的代码。

Current code: 当前代码:

@RequestMapping("/this/is/duplicate/few/times/some")
public class SomeController {
}

And I want to create something like this 我想创建这样的东西

@Retention(RetentionPolicy.RUNTIME)
@RequestMapping()
public @interface CustomRequestMapping {

    String value() default "";

    @AliasFor(annotation = RequestMapping.class, attribute = "value")
    String "/this/is/duplicate/few/times"+value();

}

In order to reduce Request Mapping value to this: 为了减少对此的请求映射值:

@CustomRequestMapping("/some")
public class SomeController {
}

Unfortunately I cant find way to make that compilable. 不幸的是,我找不到使它可编译的方法。 Or maybe there is a way to use AliasFor annotation to pass parameter into destination array. 也许有一种方法可以使用AliasFor批注将参数传递到目标数组。 Something like this: 像这样:

@Retention(RetentionPolicy.RUNTIME)
    @RequestMapping()
    public @interface CustomRequestMapping {

    @AliasFor(annotation = RequestMapping.class, attribute = "value{1}")
    String value() default "";

    @AliasFor(annotation = RequestMapping.class, attribute = "value{0}")
    String prefixPath() default "/this/is/duplicate/few/times";

}

What it seems is you are trying to make a subtype of an annotation and modify one of its attributes default value 看来您正在尝试制作注释的子类型并修改其属性之一的默认值

Subtyping of annotation is not possible and here is the JSR stating the reason. 注释的子类型化是不可能的, 是JSR说明原因。

It complicates the annotation type system,and makes it much more difficult
to write “Specific Tools”.

“Specific Tools” — Programs that query known annotation types of arbitrary
 external programs. Stub generators, for example, fall into this category.
 These programs will read annotated classes without loading them into the 
 virtual machine, but will load annotation interfaces.

One solution to your duplication problem could be to extract a constant. 解决复制问题的一种方法是提取一个常数。

@Annotation(MyClass.FOO+"localValue")
public class MyClass
{
    public static final String FOO = "foo";
    ...
}

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

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