package com.langsin.annotation;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author Lei
* @version create time:2009-10-16 下午02:28:43
*/
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String hello() default "langsin";
String world();
}
class MyTest {
@MyAnnotation(hello = "beijing", world = "shanghai")
@Deprecated
@SuppressWarnings("unchecked")// @Retention(value=SOURCE)
public void output() {
System.out.println("output something");
}
}
public class MyReflec {
public static void main(String[] args) {
MyTest myTest = new MyTest();
Class<MyTest> c = MyTest.class;
Method method = null;
try {
method = c.getMethod("output", new Class[] {});
}
catch (SecurityException e) {
e.printStackTrace();
}
catch (NoSuchMethodException e) {
e.printStackTrace();
}
if(method.isAnnotationPresent(MyAnnotation.class)) {
try {
method.invoke(myTest, new Object[] {});
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
MyAnnotation myAnnotation = method
.getAnnotation(MyAnnotation.class);
System.out.println(myAnnotation.hello());
System.out.println(myAnnotation.world());
}
Annotation[] annotations = method.getAnnotations();
for(Annotation annotation: annotations) {
System.out.println(annotation.annotationType().getName());
}
}
}