어노테이션에 대해 더 이해하고 싶어서 어노테이션을 직접 만들어보고 사용해봤다..!
/**
* Indicates that a method declaration is intended to override a
* method declaration in a supertype. If a method is annotated with
* this annotation type compilers are required to generate an error
* message unless at least one of the following conditions hold:
*
* <ul><li>
* The method does override or implement a method declared in a
* supertype.
* </li><li>
* The method has a signature that is override-equivalent to that of
* any public method declared in {@linkplain Object}.
* </li></ul>
*
* @author Peter von der Ahé
* @author Joshua Bloch
* @jls 8.4.8 Inheritance, Overriding, and Hiding
* @jls 9.4.1 Inheritance and Overriding
* @jls 9.6.4.4 @Override
* @since 1.5
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}


클래스 어노테이션으로 @Company, 메소드 어노테이션으로 @Star를 만들어봤다.
@Company 어노테이션으로 회사 정보를 넣었고 @Star 어노테이션은 메소드가 사용할 때 같이 출력될 *의 개수 정보를 넣었다.
package javastudy.temp.annotation.company;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE) // 클래스에 사용 가능
@Retention(RetentionPolicy.RUNTIME) // 런타임 시에도 사용 가능
public @interface Company { // @interface로 어노테이션 선언
String name() default "ABC"; // 어노테이션을 사용할 때 name 값을 String으로 지정할 수 있고 지정하지 않으면 기본 값은 "ABC"이다.
String city() default "XYZ"; // 어노테이션을 사용할 때 city 값을 String으로 지정할 수 있고 지정하지 않으면 기본 값은 "XYZ"이다.
}
package javastudy.temp.annotation.company;
@Company(name = "Joo")
public class Employee {
private int id;
private String name;
/**
* 생성자
* @param id
* @param name
*/
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
/**
* Employee 정보 출력
*/
public void getEmployeeDetails() {
System.out.println("Employee Id: " + id);
System.out.println("Employee Name: " + name);
}
}
package javastudy.temp.annotation.company;
import java.lang.annotation.Annotation;
public class Main {
public static void main(String[] args) {
/* employee 생성 */
Employee employee = new Employee(1, "John Doe"); // id: 1, name: John Doe
/* employee 정보 출력 */
employee.getEmployeeDetails(); // 출력: 1, John Doe
/* employee의 어노테이션 Company 가져오기 */
Annotation companyAnnotation = employee.getClass().getAnnotation(Company.class); // 클래스의 Company 어노테이션 가져오기
Company company = (Company)companyAnnotation;
/* employee의 어노테이션 Company에 지정한 값 가져오기 */
System.out.println("Company Name: " + company.name()); // Joo
System.out.println("Company City: " + company.city()); // XYZ
}
}
출력 결과
Employee Id: 1
Employee Name: John Doe
Company Name: Jack
Company City: XYZ
**********
Employee Id: 1
Employee Name: John Doe
Java에서 어노테이션(Annotation) 이란 무엇인가에 대해 알아보자.
An Introduction to Annotations and Annotation Processing in Java