Passion/Java

[Java] Custom Annotation Example @Inject

sunshout 2011. 7. 15. 07:31
Java Custom annotation : @Inject

 - JVM can read annotation in runtime with @Retention
 - if field has @Inject annotation, set value in runtime  

import java.lang.reflect.Field;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Target(FIELD)
@Retention(RUNTIME)
public @interface Inject {
    Class<?> adapter() default Object.class;
}


public class ExAnnotation {
@Inject
String field1;
String field2;
public static void main(String[] args) {
// TODO Auto-generated method stub
ExAnnotation inst = new ExAnnotation();
Field[] fields = inst.getClass().getDeclaredFields();
for (Field field: fields) {
//System.out.println(field.getName());

//This can be retrieve when runtime, using @Retention 

Inject inject = field.getAnnotation(Inject.class);
if (inject != null) {
System.out.println("Inject exist:" + field.getName());
Class<?> fc = field.getType();
boolean tf = String.class.isAssignableFrom(fc);
if (tf == true) {
try {
field.setAccessible(true);
field.set(inst , "insert default string value");
}
catch (IllegalArgumentException x) {
x.printStackTrace();
}
catch (IllegalAccessException x) {
x.printStackTrace();
}
}
}
}
System.out.println("field1:" + inst.field1);
System.out.println("field2:" + inst.field2);
}

}