IT이야기

Java 주석 구성원에 사용할 수 있는 유형은?

cyworld 2022. 5. 24. 21:58
반응형

Java 주석 구성원에 사용할 수 있는 유형은?

오늘 이 설명서에 이어 첫 번째 주석 인터페이스를 만들려고 했는데 컴파일러 오류가 발생했어.

Invalid type for annotation member":
public @interface MyAnnotation {
    Object myParameter;
    ^^^^^^
}

분명히Object주석 부재 유형으로 사용할 수 없음.불행히도 나는 어떤 타입이 일반적으로 사용될 수 있는지에 대한 어떤 정보도 찾을 수 없었다.

시행착오를 통해 알게 된 내용:

  • String→ 유효
  • int→ 유효
  • Integer→ 무효 (놀랍게도)
  • String[]→ 유효 (놀랍게도)
  • Object→ 무효

아마도 누군가는 어떤 유형이 실제로 허용되고 왜 허용되는지 어느 정도 밝혀낼 수 있을 것이다.

그것은 JLS의 9.6.1절에 명시되어 있다.주석 부재 유형은 다음 중 하나여야 한다.

  • 원시적
  • 열거형.
  • 다른 주석
  • 클래스
  • 위 사항의 배열.

그것은 제한적으로 보이지만, 의심할 여지 없이 그것에 대한 이유가 있다.

다차원 배열(예:String[][])는 위 규칙에 의해 암묵적으로 금지되어 있다.

클래스 배열은 이 답변에 설명된 대로 허용되지 않는다.

나는 이용 가능한 타입에 대해 스카프만의 의견에 동의한다.

추가 제한 : 컴파일 시간 상수여야 한다.

예를 들면 다음과 같은 것은 금지되어 있다.

@MyAnnot("a" + myConstantStringMethod())
@MyAnnot(1 + myConstantIntMethod())

또한 주석 자체는 주석 정의의 일부가 될 수 있다는 점도 잊지 마십시오.이렇게 하면 간단한 주석 중첩이 가능하여 한 개의 주석을 여러 번 표시하려는 경우에 유용하다.

예를 들면 다음과 같다.

@ComplexAnnotation({
    @SimpleAnnotation(a="...", b=3),
    @SimpleAnnotation(a="...", b=3),
    @SimpleAnnotation(a="...", b=3)
})
public Object foo() {...}

어디에SimpleAnnotation이다

@Target(ElementType.METHOD)
public @interface SimpleAnnotation {
    public String a();
    public int b();
)

그리고ComplexAnnotation이다

@Target(ElementType.METHOD)
public @interface ComplexAnnotation {
    public SimpleAnnotation[] value() default {};
)

예: blogs.oracle.com/toddfast/entry/creating_nested_complex_java_annotations://blogs.oracle.com/toddfast/entry/creating_nested_complex_java_annotations

(원래 URL: https://blogs.oracle.com/toddfast/entry/creating_nested_complex_java_annotations)

주석 개념은 내 프로젝트의 설계와 잘 맞아떨어진다. 주석 안에 복잡한 데이터 유형이 있을 수 없다는 것을 깨닫기 전까지는 말이다.나는 그 클래스의 인스턴스화된 사물보다는 내가 인스턴스화하고 싶은 클래스를 사용함으로써 그것을 극복했다.완벽하지는 않지만 자바는 거의 완벽하지 않다.

@interface Decorated { Class<? extends PropertyDecorator> decorator() }

interface PropertyDecorator { String decorate(String value) }

class TitleCaseDecorator implements PropertyDecorator {
    String decorate(String value)
}

class Person {
    @Decorated(decorator = TitleCaseDecorator.class)
    String name
}

Oracle에 따르면 주석 요소에 대한 유효한 유형은 다음과 같다.

1. Primitives (byte, char, int, long float, double)
2. Enums
3. Class (Think generics here Class <?>, Class<? extends/super T>>)
4. String
5. Array of the above (array[] of primitives, enums, String, or Class)
5. Another annotation.

게다가, 모든 요소들은 본질적으로 공공적이고 추상적인 것으로 간주된다.

그러므로

 static final variable(s) allowed as well.

참조URL: https://stackoverflow.com/questions/1458535/which-types-can-be-used-for-java-annotation-members

반응형