您的位置:首页 > 其它

Annotation(自定义注解)反射获取注解

2016-01-15 20:50 288 查看


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();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: