package com.jason.base.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
/**
* 通过反射获取类方法中的注解信息
*
* @author Administrator
*
*/
public class MyReflectTest
{
public static void main(String[] args) throws Exception
{
RetentionTest rt = new RetentionTest();
Class<RetentionTest> c = RetentionTest.class;
Method m = c.getMethod("output", new Class[] {});
if (m.isAnnotationPresent(MyAnnotation.class))
{
m.invoke(rt, new Object[] {});
MyAnnotation ma = m.getAnnotation(MyAnnotation.class);
String hello = ma.hello();
String value = ma.value();
System.out.println(hello + "," + value);
}
Annotation[] ans = m.getAnnotations();
for (Annotation an : ans)
System.out.println(an.annotationType().getName());// 只会输出runtime类型的注解
}
}
//
@MyAnnotation(value="welcome")// hello已经有默认值
public class RetentionTest
{
@MyAnnotation(hello="zhangsan", value="welcome to you")
@Deprecated
@SuppressWarnings("unchecked")
public void output()
{
System.out.println("hello world");
}
}
///
/**
* JVM运行期可以读取,即可以使用反射机制
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation
{
String hello() default "hello";
String value();
}