简体   繁体   中英

Type hierarchy in java annotations

I am facing problem with creating some metadata structure inside annotations. We are using annotations for define special attributes for hibernate entity attributes but it might be usable everywhere. I want to create condition which represent these structure:

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

Problem is that I need to define some "tree" structure using this annotations. Here is some design I want to reach:

@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 these annotation 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 inheritance in that way I defined in the annotation definition above is not possible. But how can I consider my annotations AND, OR to be in one "family"?

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

But you can create meta annotations that can be used on annotation to create groups of annotations.

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

But this will not help you with your second problem ie. use LogicalExpression as a Parent.

But you can do something like below. Declare LogicExpression as enum This way you can use single enum and various set of Attributes to execute conditions.

eg If you want to execute AND , OR condition then you can pass LogicExpression.AND , LogicExpression.OR and use orAttributes() method to execute OR condition and andAttributes() to execute 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 {};..
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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