How to use java annotation at runtime

blogs at Instant Kick

Imagine, you need to capture the information at runtime and you are looking for best feature that serve your purpose. I’ll show you how it can be achieved.

Java Annotation is very useful because it can perform many useful tasks such as

1) It can be used by the compiler to detect errors or suppress warnings,

2) Annotation information can be used to generate code, XML files etc.

3) Some annotations are also available to be evaluated at runtime that’s what you are looking for.

Lets see how annotation can be used to capture runtime information. First step is to create the annotation type.

In Listing-1,

Line 1 @Target(ElementType.TYPE) indicates that annotation can be used on type such as class or interface .

line 2 @Retention(RetentionPolicy.RUNTIME) suggests that annotation information should be available in JVM and can be accessed via reflection. Here, runTimeInfo() method is declared.

Listing-1

1

2

3

4

5

@Target( ElementType.TYPE )

@Retention( RetentionPolicy.RUNTIME )

@interface InfoAnnotation {

String runTimeInfo();

}

Listing-2 displays the code for the class we would like to monitor on runtime. This class implements the annotation created above. Here, we are overriding the method runTimeInfo() that will display the time taken by the instance to be constructed. annotationType() method returns the annotation class.

Listing-2

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

class RunTimeAnnotationExample implements InfoAnnotation {

public RunTimeAnnotationExample() {

//some code to process info

}

@Overrides

public String runTimeInfo() {

long millis = System.currentTimeMillis();

new RunTimeAnnotationExample();

millis = System.currentTimeMillis() - millis;

return "This is a RunTimeAnnotation class, running on "

+ System.getProperty("os.name")

+ ". Total time taken by constructor "

+ millis + " milliseconds.";

}

@Override

public Class annotationType() {

return InfoAnnotation.class;

}

}

You are ready with your annotation code and annotation implementation. Now, you need to utility to extract the runtime information out of these.

Listing-3, displays utility code. It is straight forward, you pass the annotation implementation class to utility constructor InfoConsoleWriter() that implicitly first create the list of such objects (if you are capturing runtime information for multiple classess) and then calls the printInformation() method, ultimately runTimeInfo() gets call.

Listing-3

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

/* import java.lang.annotation.* or other classes */

public class InfoConsoleWriter {

public InfoConsoleWriter(Class... objInfoClassPrinter) throws Exception {

List listOfInfoAnnotation = getDocumentAnnotations(objInfoClassPrinter);

printInformation(listOfInfoAnnotation);

}

private List getDocumentAnnotations(Class... objInfoClassPrinter) throws Exception {

List returnedList = new ArrayList();

for (Class c : objInfoClassPrinter)

if (c.isAnnotationPresent(InfoAnnotation.class))

returnedList.add(c.getAnnotation(InfoAnnotation.class));

else if (Arrays.asList(c.getInterfaces()).contains(InfoAnnotation.class))

returnedList.add((InfoAnnotation) c.newInstance());

return returnedList;

}

private void printInformation(List objectList) {

for (InfoAnnotation object : objectList)

System.out.println(object.runTimeInfo());

}

public static void main(String[] args) throws Exception {

new InfoConsoleWriter(RunTimeAnnotationExample.class);

}

}

Output:
This is a RunTimeAnnotation class, running on Windows 2008. Total time taken by constructor 26 milliseconds.

Similarly, you can retrieve different information at runtime.

时间: 2024-10-31 15:13:34

How to use java annotation at runtime的相关文章

Java Annotation 及几个常用开源项目注解原理简析

PDF 版: Java Annotation.pdf, PPT 版:Java Annotation.pptx, Keynote 版:Java Annotation.key 一.Annotation 示例 Override Annotation Java 1 2 3 @Override public void onCreate(Bundle savedInstanceState); Retrofit Annotation Java 1 2 3 @GET("/users/{username}&quo

第17篇-JAVA Annotation 注解

第17篇-JAVA Annotation 注解 每篇一句 :真的努力后你会发现自己要比想象的优秀很多 初学心得: 怀着一颗奋斗不息的心,一切困苦艰辛自当迎刃而解 (笔者:JEEP/711)[JAVA笔记 | 时间:2017-05-17| JAVA Annotation注解 ] 1.什么是注解(Annotation) Annotation 其实就是代码里的特殊标记, 它用于替代配置文件,也就是说,传统方式通过配置文件告诉类如何运行,有了注解技术后,开发人员可以通过注解告诉类如何运行.在Java技术

1.2.4 Java Annotation 提要

(本文是介绍依赖注入容器Spring和分析JUnit源码的准备知识) Java Annotation(标注) java.lang.annotation.Annotation是全部Java标注的父接口.它除了override/改写Object的equals(Object).hashCode()和toString()外,仅有一个方法 Class<? extends Annotation> annotationType() 返回本标注的的类型. JDK中定义的标注java.lang.Override

学习笔记之Java Annotation学习总结 [ 光影人像 东海陈光剑 的博客 ]

?? 按照自己定的学习计划,今天是该写点什么了. ? 在上篇文章里提到的是JUnit的学习,其中就涉及到了一些内置的annotation,如@Test.@Ignore等.现在我就结合个人的理解谈下如何自定义自己的annotation. ? annotation能被用来为某个程序元素(类.方法.成员变量等)关联任何的信息,但annotaion不能影响程序代码的执行,无论增加.删除annotation,代码都始终如一的执行.另外,尽管一些annotation通过java的反射api方法在运行时被访问

Java Annotation 注解

java_notation.html div.oembedall-githubrepos { border: 1px solid #DDD; list-style-type: none; margin: 0 0 10px; padding: 8px 10px 0; font: 13.34px/1.4 helvetica, arial, freesans, clean, sans-serif; width: 452px; background-color: #fff } div.oembedall

Java Annotation入门

Java Annotation入门作者:cleverpig 版权声明:本文可以自由转载,转载时请务必以超链接形式标明文章原始出处和作者信息及本声明作者:cleverpig(作者的Blog:http://blog.matrix.org.cn/page/cleverpig)原 文:[http://www.matrix.org.cn/resource/article/44/44048_Java+Annotation.html]http://www.matrix.org.cn/resource/arti

Java annotation浅析

自定义annotation @Documented@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.FIELD,ElementType.METHOD,ElementType.TYPE})public @interface TestAnnotation {    //default关键字是用来设置注解的默认值,可有可没有    String value() default("Hello,I am a field");    S

回顾java Annotation(注解)

最近在学习中发现相当多的框架是通过注解来实现的.为了加深记忆,把注解重新做一下回顾. 首先注解不是注释.--但因为java语言内置了三个注解:@Override.@Deprecated.@SuppressWarnnings.第一个是通知编译器做方法覆盖检查:第二个是提醒程序员使用了过时的方法:第三个是通知编译器忽略警告.这三个内置注解用起来给人的感觉就象注释一样.而实际上注解的用法远不止这么简单,通过使用自定义注解有助于加深我们的理解. 使用自定义注解目的是为了给程序加上某些标记(这种标记也可称

java annotation 获取属性

自定义Annotation 1.声明一个annotation,类型是@interface //声明注解 @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ValueBind { enum fieIdType { STRING, INT }; fieIdType type() default fieIdType.STRING;// 为属性提供一个默认值 Strin