在Java中如何实现自己的annotation
2014-02-08 17:30
260 查看
1. 先定义annotation
2. 使用annotation
例子:
info is awesome!
This is AWESOME
http://isagoksu.com/2009/development/java/creating-custom-annotations-and-making-use-of-them/
2. 使用annotation
例子:
import java.lang.annotation.*; import java.lang.reflect.Method; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @interface Test { String info() default ""; } class Annotated { @Test(info = "AWESOME") public void foo(String myParam) { System.out.println("This is " + myParam); } } class TestAnnotationParser { public void parse(Class clazz) throws Exception { Method[] methods = clazz.getMethods(); for (Method method : methods) { if (method.isAnnotationPresent(Test.class)) { Test test = method.getAnnotation(Test.class); String info = test.info(); if ("AWESOME".equals(info)) { System.out.println("info is awesome!"); // try to invoke the method with param method.invoke(Annotated.class.newInstance(), info); } } } } } public class Demo { public static void main(String[] args) throws Exception { TestAnnotationParser parser = new TestAnnotationParser(); parser.parse(Annotated.class); } }程序输出:
info is awesome!
This is AWESOME
http://isagoksu.com/2009/development/java/creating-custom-annotations-and-making-use-of-them/
相关文章推荐
- 如何使用网页开发自己的app,在网页中的按钮与自己的java代码绑定来实现打电话即javascript代码调用java代码,和java代码来调用javascript代码
- java 栈和Java基础类的Stack类的源码实现,缺陷以及如何实现自己的Stack类
- 如何开发一个java开源框架-----Jvn框架之实现自定义Annotation以及拦截器(第五讲)
- 用Annotation,Future,动态代理实现自己的JAVA方法运行超时应用
- 自己动手实现Java注解(Java Annotation in Action)
- 《徐徐道来话Java》(2):泛型和数组,以及Java是如何实现泛型的
- JAVA架构师必知之事 —— 如何定义自己的职业路线?
- Java实现分页功能 代码很粗糙,都是根据自己所需去定义逻辑功能的。
- 如何用Java实现Web服务器
- Java Session 是如何实现的
- 如何在Java中使用双重检查锁实现单例
- 关于 如何实践kernel/driver/u-boot ,怎么样按照作者的思路实现自己的代码
- java如何实现线程的安全:线程的同步机制
- 两个相交的圆形,第一个圆形内包含很多点,第二个圆内包含很多点,现在要求两个圆内相交的点是哪些,用随便的java或matlab算法如何实现呢?
- java 多态怎么回事,如何实现?
- 什么是java序列化,如何实现java序列化?
- 如何使用 Java8 实现观察者模式?(下)
- 如何在SpringMVC框架中利用Java反射机制和Javassist实现Java对象、属性、注解的动态创建生成
- 如何用Spring AOP和Java自定义注解实现登陆鉴权
- 请教:在java中如何实现线程的函数互斥调用,用synchronized好像实现不了