Skip to content

Instantly share code, notes, and snippets.

@karanmalhi
Created May 25, 2011 18:09
Show Gist options
  • Save karanmalhi/991522 to your computer and use it in GitHub Desktop.
Save karanmalhi/991522 to your computer and use it in GitHub Desktop.
Simple example on annotations
package com.learnquest;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
public @interface ClassPreamble {
String[] authors();
double version() default 1.0;
}
package com.learnquest;
@ClassPreamble(authors = "Alice")
public class Person {
@Value("Sarah")
private String firstName;
public Person(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Override
public String toString() {
return super.toString();
}
}
package com.learnquest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
public class Test {
public static void main(String[] args) throws Exception {
Person p = new Person(null);
System.out.println(p.getFirstName());
performDependencyInjection(p);
System.out.println(p.getFirstName());
}
private static void performDependencyInjection(Object obj) throws Exception{
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
if(field.getType().equals(String.class)){
Annotation[] annotations = field.getDeclaredAnnotations();
for (Annotation annotation : annotations) {
if(annotation.annotationType().equals(Value.class)){
// set a private field to be accessible
boolean accessible = field.isAccessible();
if(!accessible){
field.setAccessible(true);
}
// retrieve the value from annotation
Value valueAnnotation = (Value) annotation;
String value = valueAnnotation.value();
// set value on the field
field.set(obj, value);
// set accessibility back to private
field.setAccessible(accessible);
}
}
}
}
}
}
package com.learnquest;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Value {
String value();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment