标签:
演示注解的使用
用来注解类
package _4annotation._1review; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Description { String value(); }用来注解方法
package _4annotation._1review; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MethodDesc { String name(); }进行注解
package _4annotation._1review; @Description("这是传智播客上海机构,牛") public class ITCAST_SH { @MethodDesc(name="o了,老毕坐镇") public void java(){ System.out.println("this is annotation class and method"); } }对注解进行操作
package _4annotation._1review; import java.lang.reflect.Method; import org.junit.Test; public class AnnotationParse { @Test public void testParse(){ Class c = ITCAST_SH.class; //判断是否有Description这个注解类 if(c.isAnnotationPresent(Description.class)){ Description d = (Description) c.getAnnotation(Description.class); //判断Description注解类中value的值是什么 if(d.value().contains("播客")){ System.out.println("学费减半"); } } Method[] methods = c.getMethods(); for(Method mmethod : methods){ //判断类的方法是否有MethodDesc注解 if(mmethod.isAnnotationPresent(MethodDesc.class)){ MethodDesc methodDesc = (MethodDesc) mmethod.getAnnotation(MethodDesc.class); //拿到注解类的值 if(methodDesc.name().contains("老毕")){ System.out.println("折上折"); } } } } }
标签:
原文地址:http://my.oschina.net/u/2356176/blog/469112