Java cyclic annotations

I want to create a tree structure with annotation

@Retention(RetentionPolicy.RUNTIME) public @interface MyNode { String name(); MyNode next() default null; } 

but the compiler reports that it is a loop and therefore it is not allowed.

I wonder why this is not allowed and how can I do something like this?

+4
source share
3 answers
  • Annotations are compile-time constants.
  • Only compilation time constants (strings, primitives, enumerations, annotations, class literals) can be participants in annotations.
  • Everything that refers to itself cannot be a constant, so the annotation cannot refer to itself.

The funny thing is: there is part of the Java language specification that seems to contradict this:

Annotations for annotation type declarations are known as meta annotations. An annotation type can be used to annotate your own declaration. More generally, circular dots in the transitive closure of the annotate relationship are allowed. For example, it is legal to annotate an annotation type declaration with a different annotation type, and annotate a declaration of the last type with the same type. (Predefined types of meta annotations contain several such roundnesses.)
[ Source ]

But I get a compilation error for both (links to annotations themselves):

 public @interface Funky { Funky funky(); } 

and this (two annotations refer to each other):

 public @interface Funky { Monkey monkey(); } public @interface Monkey { Funky funky(); } 
+1
source

This is not a tree structure, but only a linear list. Try using an array to simplify the declaration.

 @Retention(RetentionPolicy.RUNTIME) public @interface MyNode { String name(); } 

And wrap:

 @Retention(RetentionPolicy.RUNTIME) public @interface MyNodes { MyNode[] value(); } 

Now just declare an array:

 @MyNodes({ @MyNode(name = "name1"), @MyNode(name = "name2") }) public class MyClass { } 
+2
source

If you really need it, you can use the Sun Java 5 compiler, where this restriction does not apply.

But maybe the best solution is to save the nodes in the array and let each node have the index of its child node (s).

0
source

All Articles