Type hierarchy in java annotations

冷暖自知 提交于 2019-12-13 13:23:47

问题


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"?


回答1:


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.

e.g. 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 {};..
}


来源:https://stackoverflow.com/questions/12294247/type-hierarchy-in-java-annotations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!