2009-04-08 7 views
18

Java 주석을 사용하려고하는데 내 코드가 코드를 인식하지 못하는 것 같습니다. 내가 뭘 잘못하고 있니?Java 주석이 작동하지 않습니다.

import java.lang.reflect.*; 
    import java.lang.annotation.*; 

    @interface MyAnnotation{} 


    public class FooTest 
    { 
    @MyAnnotation 
    public void doFoo() 
    {  
    } 

    public static void main(String[] args) throws Exception 
    {    
     Method method = FooTest.class.getMethod("doFoo"); 

     Annotation[] annotations = method.getAnnotations(); 
     for(Annotation annotation : method.getAnnotations()) 
      System.out.println("Annotation: " + annotation ); 

    } 
    } 
+0

당신이 사용하지 않는 '주석'지역 변수 또는 사용을 제거하기 위해 코드를 편집 할 수 있습니다 {... – blank

답변

34

주석 인터페이스에서 @Retention 주석을 사용하여 주석을 런타임 주석으로 지정해야합니다.

@Retention(RetentionPolicy.RUNTIME) 
@interface MyAnnotation{} 
23

짧은 답변 : 당신이 당신의 주석 정의에 @Retention (RetentionPolicy.RUNTIME)를 추가해야합니다.

설명 :

주석이 컴파일러에 의해 유지 기본 하지가 있습니다. 그들은 단순히 런타임에 존재하지 않습니다. 이것은 처음에 어리석게 들릴지 모르겠지만 컴파일러 (@Override) 또는 다양한 소스 코드 분석기 (@Documentation 등)에서만 사용되는 많은 주석이 있습니다.

예를 들어 리플렉션을 통해 주석을 실제로 사용하려면 클래스 파일 자체에서 해당 주석을 기록하도록 Java에 알려야합니다. 그 노트는 다음과 같습니다

자세한 내용은
@Retention(RetentionPolicy.RUNTIME) 
public @interface MyAnnotation{} 

은 공식 문서 1을 확인하고, 특히 RetentionPolicy에 대한 비트를 확인합니다.

3

사용 @Retention(RetentionPolicy.RUNTIME) 아래 코드를 확인하십시오. 나를 위해 노력하고 있습니다 (주석 주석 : 주석)을 위해 :

import java.lang.reflect.*; 
import java.lang.annotation.*; 

@Retention(RetentionPolicy.RUNTIME) 
@interface MyAnnotation1{} 

@Retention(RetentionPolicy.RUNTIME) 
@interface MyAnnotation2{} 

public class FooTest { 
    @MyAnnotation1 
    public void doFoo() { 
    } 

    @MyAnnotation2 
    public void doFooo() { 
    } 

    public static void main(String[] args) throws Exception { 
     Method method = FooTest.class.getMethod("doFoo"); 
     for(Annotation annotation : method.getAnnotations()) 
      System.out.println("Annotation: " + annotation ); 

     method = FooTest.class.getMethod("doFooo"); 
     for(Annotation annotation : method.getAnnotations()) 
      System.out.println("Annotation: " + annotation ); 
    } 
} 
관련 문제