读书人

java 诠注及其反射

发布时间: 2012-10-06 17:34:01 作者: rapoo

java 注解及其反射

自定义注解

package cn.lichaozhang.annotationreflect;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(value=RetentionPolicy.RUNTIME)public @interface MyAnnotation {public String key() default "LCZ";public String value() default "张历超";}

?应用注解

package cn.lichaozhang.annotationreflect;public class SimpleBean {@MyAnnotation(key="lichaozhang",value="www.iteye.com")public String toString(){return "Hello Annotation!!!";}}

?

注解解析器

package cn.lichaozhang.annotationreflect;import java.lang.reflect.Method;public class MyDefaultAnnotationReflect {@SuppressWarnings("unchecked")public static void main(String[] args) throws Exception {Class clazz = Class.forName("cn.lichaozhang.annotationreflect.SimpleBean");Method method = clazz.getDeclaredMethod("toString", null);if (method.isAnnotationPresent(MyAnnotation.class)) {MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);String key = myAnnotation.key();String value = myAnnotation.value();System.out.println(key + "\t" + value);}}}

?

读书人网 >软件架构设计

热点推荐