Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can java annotation have complex return type like HashMap

Can annotation have complex return type, such as HashMap.

I am looking for something like:

@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface column {     public HashMap<String, String> table(); } 

so I can have a constant annotated like(pseudo code):

@column({table=(dbName, tableName), table=(dbName, tableName2)}) public static final String USER_ID = "userid"; 

If Annotation doesn't allow you to have complex return type, then any good practice for this kind of case?

like image 878
Shengjie Avatar asked Nov 26 '12 16:11

Shengjie


People also ask

What can be used as return type for annotation method declaration?

TYPE_USE , the annotation applies to the return type. If it uses ElementType. METHOD , it applies to the method declaration. If it uses both (or none), it applies to both the return type and method declaration.

Which is not a valid return type of a method that is declared in an annotation type?

What Object Types Can Be Returned from an Annotation Method Declaration? The return type must be a primitive, String, Class, Enum, or an array of one of the previous types. Otherwise, the compiler will throw an error.

Which of the following are not type of annotation?

Which of the following is not pre defined annotation in Java? Explanation: @Overriden is not a pre defined annotation in Java. @Depricated, @Override, @SuppressWarnings, @SafeVarags and @FunctionInterface are the pre defined annotations.

Can try catch block be annotated?

2. Re: try catch around annotated method. Right approach, but Seam doesn't support method level interceptors, only class level interceptors. So you can attach the interceptor at class level, and then mark the method with the same annotation, and only intercept those.


1 Answers

No, annotation elements can only be primitive types, Strings, enum types, Class, other annotations, or arrays of any of these. The typical way to represent these kinds of structures would be to declare another annotation type

public @interface TableMapping {   public String dbName();   public String tableName(); } 

then say

@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface column {     public TableMapping[] table(); } 

And use the annotation as

@column(table={   @TableMapping(dbName="dbName", tableName="tableName"),   @TableMapping(dbName="db2", tableName="table2") }) public String userId = "userid"; 
like image 138
Ian Roberts Avatar answered Sep 24 '22 02:09

Ian Roberts