Java Annotation Examples
来源:互联网 发布:php购物车源码 编辑:程序博客网 时间:2024/05/16 02:02
Define Annotaion
import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target({ElementType.TYPE, ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)public @interface JavaFileInfo { String author() default "unknown"; String version() default "0.0";}
Use Annotation
@JavaFileInfopublic class DemoClass{ @JavaFileInfo(author = "Lokesh", version = "1.0") public String getString() { return null; }}
Processing Annotations Using Reflection
import java.lang.annotation.Annotation;import java.lang.reflect.AnnotatedElement;import java.lang.reflect.Method;public class ProcessAnnotationExample{ public static void main(String[] args) throws NoSuchMethodException, SecurityException { new DemoClass(); Class<DemoClass> demoClassObj = DemoClass.class; readAnnotationOn(demoClassObj); Method method = demoClassObj.getMethod("getString", new Class[]{}); readAnnotationOn(method); } static void readAnnotationOn(AnnotatedElement element) { try { System.out.println("\n Finding annotations on " + element.getClass().getName()); Annotation[] annotations = element.getAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof JavaFileInfo) { JavaFileInfo fileInfo = (JavaFileInfo) annotation; System.out.println("Author :" + fileInfo.author()); System.out.println("Version :" + fileInfo.version()); } } } catch (Exception e) { e.printStackTrace(); } }}
Execute Output
Finding annotations on java.lang.ClassAuthor :unknownVersion :0.0 Finding annotations on java.lang.reflect.MethodAuthor :LokeshVersion :1.0
References
Complete Java Annotations Tutorial
Compile Time Validation using Java Annotation Processor
Lesson: Annotations
阅读全文
0 0
- Java Annotation Examples
- Java Code Examples for javax.xml.bind.annotation.XmlSchema
- Jersey annotation examples
- WebServlet annotation examples
- Java SWT Table Examples
- Java Table Examples
- java wildcards examples
- JSch - Examples - Exec.java
- Java 8 forEach examples
- JAVA Annotation & 自定义Annotation
- java Annotation Annotation elements
- Java Annotation
- Java Annotation
- Java Annotation
- Java Annotation
- Java Annotation
- java annotation
- Java Annotation
- 我是如何对网站CSS进行架构的
- RNN以及LSTM的介绍和公式梳理
- MelFrequencyFilterBank API 及Mel频率滤波器
- Ajax 不支持enctype="multipart/form-data"
- 利用Pyproj进行地理投影坐标系转换
- Java Annotation Examples
- Android单元测试框架Robolectric3.0介绍(二)
- fgets函数手册误我
- 解决ntp的错误 no server suitable for synchronization found
- java保留两位小数
- Cache数据库安装及配置
- 编译并连接从helloworld.c生成的汇编代码的方法步骤
- 设计模式(22)-模板方法模式
- 接口