Skip to content

Instantly share code, notes, and snippets.

@tokland
Last active January 29, 2016 11:03
Show Gist options
  • Save tokland/2fb215efaa62095be9db to your computer and use it in GitHub Desktop.
Save tokland/2fb215efaa62095be9db to your computer and use it in GitHub Desktop.
Basic Runtime Annotation
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;
import java.lang.reflect.Method;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String name() default "";
}
class Annotated {
@MyAnnotation(name = "Mary")
public void hello(String name) {
System.out.println("Hello " + name + "!");
}
}
class AnnotationRunner {
public void run(Class<?> klass) throws Exception {
for (Method method : klass.getMethods()) {
if (method.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
String name = myAnnotation.name();
method.invoke(klass.newInstance(), name);
}
}
}
}
public class Annotations {
public static void main(String[] args) throws Exception {
AnnotationRunner runner = new AnnotationRunner();
runner.run(Annotated.class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment