Created
June 14, 2011 14:20
-
-
Save karanmalhi/1024992 to your computer and use it in GitHub Desktop.
Basic annotation processor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package learnquest; | |
import java.lang.annotation.Annotation; | |
import java.lang.reflect.Field; | |
public class ObjectFactory { | |
public static <T> T create(Class<T> clazz) throws Exception { | |
T instance = clazz.newInstance(); | |
processAnnotations(instance); | |
return instance; | |
} | |
private static void processAnnotations(Object instance) throws Exception { | |
// find all annotations at class level and print them | |
printClassLevelAnnotations(instance); | |
printFieldLevelAnnotations(instance); | |
injectDependenciesOnFields(instance); | |
} | |
private static void injectDependenciesOnFields(Object instance) throws Exception { | |
Field[] declaredFields = instance.getClass().getDeclaredFields(); | |
for (Field field : declaredFields) { | |
Annotation[] declaredAnnotations = field.getDeclaredAnnotations(); | |
for (Annotation annotation : declaredAnnotations) { | |
if(annotation instanceof Inject){ | |
Inject inject = (Inject) annotation; | |
String value = inject.value(); | |
boolean accessible = field.isAccessible(); | |
field.setAccessible(true); | |
field.set(instance, value); | |
field.setAccessible(accessible); | |
} | |
} | |
} | |
} | |
private static void printFieldLevelAnnotations(Object instance) { | |
System.out | |
.println("**************FIELD LEVEL ANNOTATIONS******************"); | |
Field[] fields = instance.getClass().getDeclaredFields(); | |
for (Field field : fields) { | |
Annotation[] declaredAnnotations = field.getDeclaredAnnotations(); | |
for (Annotation annotation : declaredAnnotations) { | |
System.out.println(annotation); | |
} | |
} | |
} | |
private static void printClassLevelAnnotations(Object instance) { | |
System.out | |
.println("**************CLASS LEVEL ANNOTATIONS******************"); | |
Annotation[] declaredAnnotations = instance.getClass() | |
.getDeclaredAnnotations(); | |
for (Annotation annotation : declaredAnnotations) { | |
System.out.println(annotation); | |
} | |
} | |
public static void main(String[] args) throws Exception { | |
Person person = create(Person.class); | |
String firstName = person.getFirstName(); | |
System.out.println("Person has a firstname of "+firstName); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment