본문 바로가기
Java 배우기

Annotations Basics

by 노화방지 Anti-aging Hairstyle 2016. 1. 5.
반응형

The Format of an Annotation

제일 간단한 폼의 주석은 아래와 같습니다:
In its simplest form, an annotation looks like the following:

@Entity


at sign 글자(@)는 @)뒤에 오는 것은 주석임을 컴파일러에게 알려줍니다. 

아래 예제에서 주석의 이름은 Override 입니다:
The at sign character (@) indicates to the compiler that what follows is an annotation. In the following example, the annotation's name is Override:

@Override
void mySuperMethod() { ... }


주석에는 elements가 포함될 수 있는데, 이들 엘리먼트는 이름이 있을 수도 없을 수도 있으며, 이들 엘리먼트는 값을 갖고 있습니다:
The annotation can include elements, which can be named or unnamed, and there are values for those elements:


@Author(
   name = "Benjamin Franklin",
   date = "3/27/2003"
)
class MyClass() { ... }

or

@SuppressWarnings(value = "unchecked")
void myMethod() { ... }

If there is just one element named value, then the name can be omitted, as in:

@SuppressWarnings("unchecked")
void myMethod() { ... }

If the annotation has no elements, then the parentheses can be omitted, as shown in the previous @Override example.

It is also possible to use multiple annotations on the same declaration:

@Author(name = "Jane Doe")
@EBook
class MyClass { ... }

If the annotations have the same type, then this is called a repeating annotation:

@Author(name = "Jane Doe")
@Author(name = "John Smith")
class MyClass { ... }

Repeating annotations are supported as of the Java SE 8 release. For more information, see Repeating Annotations.

The annotation type can be one of the types that are defined in the java.lang or java.lang.annotation packages of the Java SE API. In the previous examples, Override and SuppressWarnings are predefined Java annotations. It is also possible to define your own annotation type. The Author and Ebook annotations in the previous example are custom annotation types.

Where Annotations Can Be Used

Annotations can be applied to declarations: declarations of classes, fields, methods, and other program elements. When used on a declaration, each annotation often appears, by convention, on its own line.

As of the Java SE 8 release, annotations can also be applied to the use of types. Here are some examples:

  • Class instance creation expression:
        new @Interned MyObject();
    
  • Type cast:
        myString = (@NonNull String) str;
    
  • implements clause:
        class UnmodifiableList<T> implements
            @Readonly List<@Readonly T> { ... }
    
  • Thrown exception declaration:
        void monitorTemperature() throws
            @Critical TemperatureException { ... }
    

This form of annotation is called a type annotation. For more information, see Type Annotations and Pluggable Type Systems.


반응형

댓글