您的位置:首页 > 其它

使用反射来提取注解annotation

2016-06-27 16:10 246 查看
package com.samsung.TextFileTest;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;

public class AnotitaionDemo {

public static void main(String[] args) throws Exception {
Class<?> classtype=Class.forName("com.samsung.TextFileTest.AnotitionTest");
boolean annotationPresent = classtype.isAnnotationPresent(Description.class);
if (annotationPresent) {
Description annotation = classtype.getAnnotation(Description.class);
System.out.println(annotation.value());
}

Method[] declaredMethods = classtype.getDeclaredMethods();
for (Method method : declaredMethods) {
if(method.isAnnotationPresent(Author.class)){
Author author=(Author)method.getAnnotation(Author.class);
System.out.println("name="+author.name()+",group="+author.group());
}
}

}
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
@interface Author {
String name();

String group();
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@interface Description {
String value();
}

@Description("这是一个AnotitionTest类")
class AnotitionTest {
@Author(name = "zhanghao", group = "SW")
public void test() {
System.out.println("this is a test");
}
}


这是一个AnotitionTest类
name=zhanghao,group=SW
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: