graczun
graczun

Reputation: 582

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.

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. 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";

}

Upvotes: 0

Views: 633

Answers (2)

AkikG
AkikG

Reputation: 71

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.

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.

Upvotes: 2

Aaron
Aaron

Reputation: 881

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";
    ...
}

Upvotes: 0

Related Questions