package com.ygl.annotion;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.
RUNTIME)
public @interface MyAnnotation {
String hello() default "ygl";
String world();
}
//*************************************
package com.ygl.annotion;
@MyAnnotation(hello="beijing",world="shanghai")
public class MyTest {
@MyAnnotation(hello="tianjin",world="shanghai")
@Deprecated
@SuppressWarnings("unchecked")
public void output(){
System.out.println("output something");
}
}//*************************************
package com.ygl.annotion;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class MyReflection {
public static void main(String[] args) throws Exception {
MyTest myTest=new MyTest();
Class<MyTest> c=MyTest.class;
try {
Method method=c.getDeclaredMethod("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();
/*@MyAnnotation(hello="tianjin",world="shanghai")
@Deprecated
@SuppressWarnings("unchecked")-->source
public void output(){
System.out.println("output something");
}*/
for(Annotation annotation:annotations){
System.out.println(annotation.annotationType().getName());
//輸出//com.ygl.annotion.MyAnnotation --》RUNTIME
//java.lang.Deprecated --》RUNTIME
}
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}