java注释可以有像HashMap这样的复杂返回类型吗
注释可以具有复杂的返回类型,例如HashMap 我正在寻找类似于:java注释可以有像HashMap这样的复杂返回类型吗,java,collections,annotations,Java,Collections,Annotations,注释可以具有复杂的返回类型,例如HashMap 我正在寻找类似于: @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface column { public HashMap<String, String> table(); } 如果注释不允许您使用复杂的返回类型,那么这种情况下有什么好的做法吗?否,注释元素只能是基元类型、字符串、enum类型、Class、其他注释或其中任
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface column {
public HashMap<String, String> table();
}
如果注释不允许您使用复杂的返回类型,那么这种情况下有什么好的做法吗?否,注释元素只能是基元类型、字符串、
enum
类型、Class
、其他注释或其中任何一种的数组。表示这类结构的典型方法是声明另一种注释类型
public @interface TableMapping {
public String dbName();
public String tableName();
}
然后说
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface column {
public TableMapping[] table();
}
并将注释用作
@column(table={
@TableMapping(dbName="dbName", tableName="tableName"),
@TableMapping(dbName="db2", tableName="table2")
})
public String userId = "userid";
几年后,我们看到了Java8。它提供了一种重复同一类注释的方法 在Java8中,您可以将注释声明为隐式包装在容器注释中。您将要重复的注释声明为
@Repeated(value=a_class)
。当您添加一个可重复注释的多个实例时,编译器将自动将这些实例包装在容器注释a_类
中,该类被指定为@Repeated
的参数
如果您声明:
@Retention(RetentionPolicy.RUNTIME)
public @interface Columns {
Column[] value() default {};
}
@Retention(RetentionPolicy.RUNTIME)
@Repeatable( value = Columns.class )
public @interface Column {
String dbName();
String tableName();
}
然后,您可以多次使用注释并将其包装到另一个注释中,也可以不将其包装到另一个注释中,两者都是等效的:
@Column(dbName="db1", tableName="table1")
@Column(dbName="db2", tableName="table2")
public static final String USER_ID = "userid";
@Columns({
@Column(dbName="db3", tableName="table3"),
@Column(dbName="db4", tableName="table4")
})
public static final String LAST_NAME = "last name";
在这两种情况下,都使用getAnnotationsByType(class)
检索注释
public static void main(String[] args) {
for( Field field : AnnotationsTest.class.getDeclaredFields() ){
System.out.println("Field: " + field.getName());
Column[] columns = field.getAnnotationsByType(Column.class);
for( Column column : columns ){
System.out.println(" db: " + column.dbName() + " table: " + column.tableName());
}
System.out.println();
}
}
它应该输出:
Field: USER_ID
db: db1 table: table1
db: db2 table: table2
Field: LAST_NAME
db: db3 table: table3
db: db4 table: table4
不要忘记枚举和classes@IanRoberts我也做过类似的事情,有点烦人,如果你只使用@table,即使有些列只有一个TableMapping,也必须有@table和一个@TableMapping。如果开始对具有多个tablemapping的字段使用@table,而对只有一个tablemapping的列使用@tablemapping。但是后一种情况将有一个更复杂的检索方法,例如getColumnsTablea()。这是一个很好的问题。。
Field: USER_ID
db: db1 table: table1
db: db2 table: table2
Field: LAST_NAME
db: db3 table: table3
db: db4 table: table4