java 주석(1)
                                            
 6641 단어  주해annotation
                    
classs와interface와 마찬가지로 주해도 하나의 유형에 속한다.메모는 @interface 키워드를 통해 정의됩니다.public @interface TestAnnotation {
}  2. 문법
기본적으로 Annotation은 인터페이스, 클래스, 메소드 등 모든 프로그램 요소를 손질하는 데 사용됩니다.
Annotation     방법론으로 정의Annotation의 멤버 변수는 참조가 없는 방법으로 선언됩니다.몇 개의 구성원 변수를 정의했는데, 사용할 때 반드시 값을 주어야 한다.
public @interface MyTag {
    String name();
    int age();
}  사용할 때 값을 주지 않을 수 있는 기본값이 있습니다.
public @interface MyTag {
    String name() default "hobe";
    int age() default 18;
}  원
Annotationjdk는java를 제외하고.lang 의 5 가지 기본 Annotation:이외에도
java.lang.annotation 가방 아래에 6개Meta Annotation(원 Annotation)가 제공됐으며, 이 중 5개는 모두 다른 것을 수식하는 데 사용Annotation됐다.주요 기능은 다음과 같습니다.1 @Retention
수식 Annotation 정의만 수식할 수 있으며 수식 기간과 소스를 지정할 수 있습니다.
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
    /**
     * Returns the retention policy.
     * @return the retention policy
     */
    RetentionPolicy value();
}  그중에는 단지 하나의 구성원 변수만 있다.
public enum RetentionPolicy {
    /**
     * Annotations are to be discarded by the compiler.
     */
    SOURCE,
    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     */
    CLASS,
    /**
     * Annotations are to be recorded in the class file by the compiler and
     * retained by the VM at run time, so they may be read reflectively.
     *
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME
}
  SOURCE: 코드를 검사하고 컴파일할 때 잃어버립니다.(주로 IDE의 오류 보고 여부에 따름)CLASS: (기본값).컴파일한 후에도class 파일에 기록될 것입니다.실행 시 JVM은 Annotation 정보를 가져올 수 없으며 반사적으로 가져올 수 없습니다.RUNTIME: (보통 사용).컴파일한 후에도class 파일에 기록될 것입니다.실행 시 JVM은 Annotation 정보를 가져오고 반사적으로 가져옵니다.사용 예:
@Retention(RetentionPolicy.RUNTIME)
public @interface MyTag {
    ...
}  또는:
@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyTag {
    ...
}  설명:
Annotation 구성원 변수의 이름이
value시value에 값만 지정하면괄호 안에value의 값을 직접 쓸 수 있으며
name=value 형식이 필요 없습니다.2 @Target
Annotation 정의만 손질할 수 있습니다.사용할 수 있는 프로그램 유닛을 지정합니다. 소스:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
    /**
     * Returns an array of the kinds of elements an annotation type
     * can be applied to.
     * @return an array of the kinds of elements an annotation type
     * can be applied to
     */
    ElementType[] value();
}  public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,
    /** Field declaration (includes enum constants) */
    FIELD,
    /** Method declaration */
    METHOD,
    /** Formal parameter declaration */
    PARAMETER,
    /** Constructor declaration */
    CONSTRUCTOR,
    /** Local variable declaration */
    LOCAL_VARIABLE,
    /** Annotation type declaration */
    ANNOTATION_TYPE,
    /** Package declaration */
    PACKAGE,
    /**
     * Type parameter declaration
     *
     * @since 1.8
     */
    TYPE_PARAMETER,
    /**
     * Use of a type
     *
     * @since 1.8
     */
    TYPE_USE
}
  멤버 변수만 손질할 수 있는 경우 다음을 사용합니다.
@Target({ElementType.FIELD})  3 @Documented
Annotation에 의해 수정된 클래스는 javadoc 도구에서 문서로 추출됩니다.
4 @Inherited
@Inherited로 장식된 주석입니다. 부모 클래스에 사용할 때 하위 클래스가 자동으로 주석을 추가합니다.
System.out.println(ChildClass.class.isAnnotationPresent(MyTag.class));  true입니다.3. 사용자 정의
Annotation분류:   Annotation 및    AnnotationAnnotation에 구성원 변수가 포함되어 있는지 여부에 따라 두 가지 범주로 분류됩니다.메모에는 속성이 없습니다.예컨대
public @interface Perform {}  그러면 이 주해를 응용할 때 괄호를 모두 생략할 수 있다.
@Perform
public void testMethod(){}  예:
@Target({ElementType.FIELD})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyTag {
    String name() default "hobe"; //   
    int age() default 18;  //int
    String[] likes(); //   
    Sex sex(); //  
}  반사 추출 Annotation 정보
Annotation을 사용하여 클래스, 메서드, 멤버 변수 등의 멤버를 수식한 후에도 이러한 Annotation은 스스로 효력이 발생하지 않습니다.개발자가 정보를 추출하고 처리해야 합니다.java.lang.reflect는 실행 중인 Annotation을 읽는 능력을 증가시킵니다.예:
Mytag 메모에서 info 메모에 있는 모든 메모를 가져오는 경우:
 Class.forName("MyTag").getMethods("info").getAnnotations()  사용 예
@Target({ElementType.FIELD,ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyTag {
    String name() default "hobe"; //   
    int age() default 18;  //int
    String[] likes(); //   
    Sex sex() default Sex.BOY; //  
}  public enum Sex {
    BOY,GIRL
}  @MyTag(likes = {"code","ball"})
public class Demo {
    private String name;
    private Integer age;
    private String[] likes;
    private Sex sex;
    public static void main(String[] args) {
        Demo demo = new Demo();
        /**     ,       Demo    */
        System.out.println(demo);
        boolean hasAnnotation = Demo.class.isAnnotationPresent(MyTag.class);
        if (hasAnnotation){
            MyTag myTag = Demo.class.getAnnotation(MyTag.class);
            System.out.println(myTag.name());
            System.out.println(myTag.likes());
            System.out.println(myTag.sex());
            System.out.println(myTag.age());
        }
    }
    ...
}  결과:
Demo{name='null', age=null, likes=null, sex=null}
hobe
[Ljava.lang.String;@4617c264
BOY
18  참조:
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
spring에서 @value 주석에 주의해야 할 문제우선, @value는 매개 변수가 필요합니다. 여기 매개 변수는 두 가지 형식이 될 수 있습니다. @Value("#{configProperties['t1.msgname']}") 또는 @Value("${t1.msgna...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.