2013-09-28 3 views
0

"InHouse"라는 사용자 정의 주석이 있습니다. 주석의 동적 값 할당

@Target(value = ElementType.FIELD) 
@Retention(value = RetentionPolicy.RUNTIME) 
public @interface InHouse { 

public String[] parentClassNames() default {}; 
} 

나는 내 주석을 지정 이처럼

public class Person{ 

    @InHouse(parentClassNames={"com.amar.Contact"}) 
    public Contact contact; 
} 

처럼 하나 개의 내 POJO 클래스에이 주석을 적용했다. 그래서 값 (parentClassNames)을 지정할 때 완전 정규 클래스 이름을 하드 코딩 했으므로 "Contact.class.getName()"처럼 액세스 할 수있는 방법이 있습니다. 이것을 사용할 때 컴파일 문제가 발생합니다. 그럼 내가 어떻게 이걸 얻을 수 있니?

나는 이렇게하고 싶다.

public class Person{ 

    @InHouse(parentClassNames={Contact.class.getName()}) 
    public Contact contact; 
} 

는이를 위해 어쨌든 있나요 ...?

답변

3

반영 시간 클래스 이름을 컴파일 할 때 알 수 없으므로 불가능합니다. 주석 값 매개 변수 유형을 클래스 []로 변경할 수 있습니다.

@Target(value = ElementType.FIELD) 
@Retention(value = RetentionPolicy.RUNTIME) 
@interface InHouse { 

    public Class[] parentClassNames() default {}; 
} 

public class Person{ 

    @InHouse(parentClassNames={Integer.class, String.class}) //Integer and String 
//are just as example, i know they are final and cant be parent classes :) 
    public Contact contact; 
} 

당신이 나중에 주석을 처리 할 때 클래스 객체에서 클래스 이름을 구하기 힘든되지 않습니다 : 그럼 당신은 당신이 원하는 것처럼 사용할 수 있습니다.