现在的位置: 首页 > 综合 > 正文

Annotations

2013年12月01日 ⁄ 综合 ⁄ 共 1603字 ⁄ 字号 评论关闭
文章目录

combine metadata with source-code files,instead of keeping it in external documents

They provide information that you need to fully describe your program,but that cannot be expressed in Java.

javal.lang

          @Override

          @Deprecated

          @SuppressWarnings

Basic syntax

   Syntactically,annotations are used in much the same way a modifiers.

Defining annotations

  compile to class files
 @Target defines where you can apply this annotation(a method or a field,for example)
@Retention defines whether the annotations are available in the source code(SOUCE),in the class files(CLASS),or at run time(RUNTIME).

Meta-annotations

@Target
@Retention
@Documented
@Inherited

Writing annotation processors

 

public <T extends Annotation>  java.lang.reflect.Method.getAnnotation(Class<T> annotationClass)
public Method[] getDeclaredMethods()
                            throws SecurityException

Annotation elements

Here is a list of the allowed types for annotation elements:
All primitives(int,float,boolean etc.)
String
Class
enums
Annotations
Arrays of any of the above

Default value constraints

elements must either have default values or values provided by the class that uses the annotation.
none of the non-primitive type elements are allowed to take null as a value.

Generating external files

If you define an element on an annotation with the name value,then as long as it is the only element type specified you don't need to use the name-value pair syntax:you can just specify the value in parentheses.

Alternative solutions 

when using multiple annotations,you cannot use the same annotation twice.
how not to use the rather long-winded name-value pair form for this nested annotation,respecifying the element name and the @interface name

Annotations don't support inheritance

Implementing the processor

public Annotation[] java.lang.reflect.Field.getDeclaredAnnotations()

抱歉!评论已关闭.