java cyclic annotations
I want to create tree structure with annotation
@Retention(RetentionPolicy.RUNTIME)
public @interface MyNode {
String name();
MyNode next() default null;
}
but compiler tells that it is cycle and hence it is not allowed.
I wonder why it is not开发者_如何学JAVA allowed and how can I make something like it?
It is not a tree structure, just the linear list. Try to use array to simplify declaration.
@Retention(RetentionPolicy.RUNTIME)
public @interface MyNode {
String name();
}
And wrap:
@Retention(RetentionPolicy.RUNTIME)
public @interface MyNodes {
MyNode[] value();
}
Now, just declare as array:
@MyNodes({
@MyNode(name = "name1"),
@MyNode(name = "name2")
})
public class MyClass {
}
- Annotations are compile-time constants.
- Annotation members can only be compile-time constants (Strings, primitives, enums, annotations, class literals).
- Anything that references itself can't be a constant, so an annotation can't reference itself.
The funny thing is: there is a part of the Java Language specification that seems to contradict this:
An annotation on an annotation type declaration is known as a meta-annotation. An annotation type may be used to annotate its own declaration. More generally, circularities in the transitive closure of the "annotates" relation are permitted. For example, it is legal to annotate an annotation type declaration with another annotation type, and to annotate the latter type's declaration with the former type. (The pre-defined meta-annotation types contain several such circularities.)
[Source]
But I get a compile error for both this (annotation references itself):
public @interface Funky {
Funky funky();
}
and this (two annotations reference each other):
public @interface Funky {
Monkey monkey();
}
public @interface Monkey {
Funky funky();
}
If you really need this, you may want to use the Sun Java 5 compiler, where this restriction is not enforced.
But maybe a better solution is to store the nodes in an array and let each node have the index(es) of it's child node(s).
精彩评论