首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

java 诠注及其反射

2012-10-06 
java 注解及其反射自定义注解package cn.lichaozhang.annotationreflectimport java.lang.annotation.Ele

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);}}}

?

热点排行