Annotation을 선언하고 사용하는 예
Annotation의 선언
package com.itbank.java.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME) //Runtime시에 Annotation에 접근하려면 반드시 필요함
public @interface MyInject {
String value();
int num();
Class object();
int[] nums();
}
프로그램 실행중에 사용될 클래스
package com.itbank.java.annotation;
public class MyClass {
public void sample(){
System.out.println("This is MyClass.sample() method.");
}
}
Annotation을 사용하는 예
package com.itbank.java.annotation;
import java.lang.annotation.*;
import java.lang.reflect.*;
public class AnnotationTest {
private MyClass myObject;
@MyInject(
num=100,
nums={1,2,3,4,5},
object=MyClass.class,
value="Annotation name: MyInject"
)
public void setMyObject() throws Exception {
Class c = this.getClass();
Method m = c.getMethod("setMyObject");
MyInject a = m.getAnnotation(MyInject.class);
int num = a.num();
int[] nums = a.nums();
Class cls = a.object();
String value = a.value();
myObject = (MyClass)cls.newInstance();
System.out.println("num="+num);
System.out.println("nums="+nums);
System.out.println("value="+value);
System.out.println("cls="+cls);
}
public static void main(String[] args) throws Exception {
AnnotationTest at = new AnnotationTest();
at.setMyObject();
at.myObject.sample();
}
}