java中输出自定义注解的实际内容

关于java自定义anootation的介绍见:http://jackyrong.iteye.com/blog/1900712

这里的一个例子,是输出一个使用了java自定义注解的实际内容的例子:


@Retention(RetentionPolicy.RUNTIME)

public @interface DeveloperInfo {



String date();



String name();



String title();



String version();



}




上面是一个注解,接下来是使用上面的注解:


@DeveloperInfo(name = "A Random Coder", title = "King Lazy", date = "2010/10/01",

version = "1.0")

@SuppressWarnings("all") //this is here for a reason <img class="wp-smiley" alt=";-)" src="http://reegz.co.za/wp-includes/images/smilies/icon_wink.gif">

public class ARandomClass {



public void aRandomMethod() {

// Some very random code...

}



@DeveloperInfo(name = "Joe Dirt", title = "Codename: The Cleaner",

date = "2010/09/01", version = "1.0")

public void doSomeRealWork() {

// Some real code here...

}

}



再来一个测试类,要输入这个类到底使用的是注解的什么属性以及其值:

public class AnnotationTest {



@SuppressWarnings("unchecked")

public static void main(String[] args) {

// An instance of the class which uses the annotation.

ARandomClass aRandomClass = new ARandomClass();



Class clazz = aRandomClass.getClass();



for (Annotation annotation : clazz.getAnnotations()) {

System.out.printf("Class-level annotation of type: %1$s n", annotation.annotationType());

}



try {

Method[] methods = clazz.getMethods();

for (Method method : methods) {

DeveloperInfo info = method.getAnnotation(DeveloperInfo.class);

if (info != null) {

System.out.printf("Method %1$s contains the DeveloperInfo annotation.n",

method.getName());

printAnnotationInfo(info);

}

}

} catch (Exception e) {

e.printStackTrace();

}

}



/**

* Outputs the data stored in the annotation.

*

* @param info

*/

private static void printAnnotationInfo(DeveloperInfo info) {

System.out.printf("tName: %1$s, Title:%2$s, Date:%3$s, Version:%4$sn",

info.name(), info.title(), info.date(), info.version());

}



}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值