Type hierarchy in java annotations

I ran into the problem of creating some kind of metadata structure inside annotations. We use annotations to define special attributes for hibernation entity attributes, but they can be used everywhere. I want to create a condition that represents this structure:

attribute1 = ... OR (attribute2 = ... AND attribute3 = ...) 

The problem is that I need to define some β€œtree-like” structure using these annotations. Here is the design I want to achieve:

 @interface Attribute { ... some attributes ... } @interface LogicalExpression { } @interface OR extends LogicalExpression { Attribute[] attributes() default {}; LogicalExpression logicalExpressions() default {}; } @interface AND extends LogicalExpression { Attribute[] attributes() default {}; LogicalExpression logicalExpressions() default {}; } @interface ComposedCondition { Attribute[] attributes() default {}; LogicalExpression logicalExpressions() default {}; } 

All of these annotations that I want to use according to this example:

 public class Table { @ComposedCondition(logicalExressions = { @OR(attributes = {@Attribute(... some settings ...)}, logicalExpressions = { @AND(attributes = {@Attribute(...), @Attribute(...)}) }) } private String value; } 

I know that inheriting in the way that I defined in the definition of annotation above is not possible. But how can I view my annotations AND, OR be in the same "family"?

+4
source share
1 answer

Please check. Why is it not possible to extend annotations in java?

But you can create meta annotations that you can use for annotations to create annotation groups.

  @LogicalExpression @interface OR { Attribute[] attributes() default {}; LogicalExpression logicalExpressions() default {}; } 

But this will not help you with your second problem, i.e. use LogicalExpression as a parent.

But you can do something like below. Declare LogicExpression as enum So you can use a single enum and a different set of Attributes to fulfill the conditions.

eg. If you want to fulfill the AND , OR condition, then you can pass LogicExpression.AND , LogicExpression.OR and use the orAttributes() method to fulfill the OR condition and andAttributes() to fulfill the AND condition

 public enum LogicExpression { OR,AND,NOT; } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface ComposedCondition { LogicExpression[] getExpressions() default {}; Attributes[] orAttributes() default {}; Attributes[] andAttributes() default {};.. } 
+5
source

Source: https://habr.com/ru/post/1432638/


All Articles