import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Retention;
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation
{
String hello() default "mylove";
String world();
}
@MyAnnotation(hello="beijing",world="shanghai")//注解用语修饰类本身
public class MyTest
{
@MyAnnotation(hello="nanjing",world="chengdu")
@Deprecated
@SuppressWarnings("unchecked")
public void output()
{
System.out.println("output something");
}
}
import java.lang.reflect.*;
import java.lang.annotation.*;
public class MyReflection
{
public static void main(String args[])throws Exception
{
MyTest mytest=new MyTest();
Class<MyTest> classType=MyTest.class;
Method method=classType.getMethod("output",new Class[]{});
if(method.isAnnotationPresent(MyAnnotation.class))
{
method.invoke(mytest,new Object[]{});
MyAnnotation myannotation=method.getAnnotation(MyAnnotation.class);
String hello=myannotation.hello();
String world=myannotation.world();
System.out.println(hello+" , "+world);
}
Annotation [] annotations=method.getAnnotations();
for(Annotation annotation:annotations)
{
System.out.println(annotation.annotationType().getName());
}
}
}
RetentionPolicy用于修饰注解能否被JVM所读取
最新推荐文章于 2022-04-11 18:13:12 发布