Java parameter types of annotation introduce

I encountered the problem of Java annotation parameters in practical applications, and the reasons are recorded here.

definition

Annotation represents syntactic metadata that can be added to Java source code. Classes, methods, variables, parameters, and packages can all be annotated, which can be used to associate information metadata with program elements.

Parameter Type

It is clearly stipulated in the JLS document that the Java annotation parameter type must be one of the following lists, otherwise a compilation error will be thrown:

  • All basic data types (int, float, boolean, byte, double, char, long, short)
  • String type
  • Class type
  • Enum type
  • Annotation type
  • and arrays of all types above
question

The following two problems are encountered in practical application.

  1. Why are other types not supported?
  2. Why are object methods not supported in annotation parameters?

#1

In Java, annotations can only be used with weaver constants, and String is also a specially treated constant, so it is a supported type. For variables, it involves initialization, serialization and other issues. For some reason, it is currently not supported in Java annotations, and it may be a choice.

For a clearer understanding of the reason, see 4.7.16.1. The element_value structure of the JVM Specification (Java SE 8 Edition) for the relevant provisions on the value of the annotation element.

First of all, in the Class file, all primitive types, String, and Class constants have special support. For general Object objects, interfaces and enum constants are not supported. The detailed analysis is as follows: https://docs.oracle.com/ javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.16.1-130 

According to the JLS specification, we know that the parameter of Annotation is also a compile-time constant, and must be supported by the Class file, indicating that Java does not want to make too many changes to the Class file and JVM for an Annotation.

However, in practical applications, we will find that this greatly reduces the ability of annotations. If interface or enum can be supported, the applicability of annotations will be greatly improved, and it is expected that it can be improved in later versions of java.

 

#2

Annotation parameter not only cannot be Object, but also because its parameter must be a compile-time constant, for example, the following writing method is illegal

 

@MyAnnotatiion(value="name"+myobject.doSomeThing())
 For more information, please refer to https://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#jls-9.6.1

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326177238&siteId=291194637