Created
July 28, 2011 21:25
-
-
Save karanmalhi/1112598 to your computer and use it in GitHub Desktop.
Challenge to invoke methods using reflection and annotation processing
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.annotation.ElementType; | |
import java.lang.annotation.Retention; | |
import java.lang.annotation.RetentionPolicy; | |
import java.lang.annotation.Target; | |
import java.lang.reflect.Field; | |
import java.util.Date; | |
public class Test { | |
public static void main(String[] args) throws Exception { | |
Foo foo = (Foo) ObjectFactory.create(Foo.class); | |
System.out.println(foo.creationTime); | |
} | |
} | |
class ObjectFactory { | |
public static Object create(Class clazz) throws Exception { | |
Object object = clazz.newInstance(); | |
Field[] fields = clazz.getDeclaredFields(); | |
for (Field field : fields) { | |
Annotation[] annotations = field.getDeclaredAnnotations(); | |
for (Annotation annotation : annotations) { | |
if (annotation instanceof Timestamp) { | |
Date now = new Date(); | |
boolean accessible = field.isAccessible(); | |
field.setAccessible(true); | |
field.set(object, now); | |
field.setAccessible(accessible); | |
} | |
} | |
} | |
// find all methods which is annotated with @PostConstruct | |
// and invoke them. | |
Method[] methods = clazz.getDeclaredMethods(); | |
for (Method method : methods) { | |
Annotation[] annotations = method.getDeclaredAnnotations(); | |
for (Annotation annotation : annotations) { | |
if(annotation instanceof PostConstruct){ | |
method.invoke(object, (Object[])null); | |
} | |
} | |
} | |
return object; | |
} | |
} | |
@Target(ElementType.TYPE) | |
@interface Info { | |
Author[] author(); | |
double version() default 1.0; | |
} | |
@interface Author { | |
String fn(); | |
String ln() default ""; | |
} | |
@Retention(RetentionPolicy.RUNTIME) | |
@Target(ElementType.FIELD) | |
@interface Timestamp { | |
} | |
@Retention(RetentionPolicy.RUNTIME) | |
@Target(ElementType.METHOD) | |
@interface PostConstruct { | |
} | |
class Foo { | |
@Timestamp | |
Date creationTime; | |
@PostConstruct | |
public void init(){ | |
System.out.println("Init method called"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment