Last active
January 29, 2016 11:03
-
-
Save tokland/2fb215efaa62095be9db to your computer and use it in GitHub Desktop.
Basic Runtime Annotation
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
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