注解(一)
转自 https://zhuanlan.zhihu.com/p/27643133
实例一:
package com.anno.test; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface Jiancha { }
package com.anno.test; public class NoBug { @Jiancha public void suanShu(){ System.out.println("1234567890"); } @Jiancha public void jiafa(){ System.out.println("1+1="+1+1); } @Jiancha public void jiefa(){ System.out.println("1-1="+(1-1)); } @Jiancha public void chengfa(){ System.out.println("3 x 5="+ 3*5); } @Jiancha public void chufa(){ System.out.println("6 / 0="+ 6 / 0); } public void ziwojieshao(){ System.out.println("我写的程序没有 bug!"); } }
package com.anno.test; import java.lang.reflect.Method; public class TestTool { public static void main(String[] args) { NoBug testobj = new NoBug(); Class clazz = testobj.getClass(); Method[] method = clazz.getDeclaredMethods(); //用来记录测试产生的 log 信息 StringBuilder log = new StringBuilder(); // 记录异常的次数 int errornum = 0; for ( Method m: method ) { // 只有被 @Jiecha 标注过的方法才进行测试 if ( m.isAnnotationPresent( Jiancha.class )) { try { m.setAccessible(true); m.invoke(testobj, null); } catch (Exception e) { // TODO Auto-generated catch block //e.printStackTrace(); errornum++; log.append(m.getName()); log.append(" "); log.append("has error:"); log.append("\n\r caused by "); //记录测试过程中,发生的异常的名称 log.append(e.getCause().getClass().getSimpleName()); log.append("\n\r"); //记录测试过程中,发生的异常的具体信息 log.append(e.getCause().getMessage()); log.append("\n\r"); } } } log.append(clazz.getSimpleName()); log.append(" has "); log.append(errornum); log.append(" error."); // 生成测试报告 System.out.println(log.toString()); } }
输出:
1234567890 1+1=11 1-1=0 3 x 5=15 chufa has error: caused by ArithmeticException / by zero NoBug has 1 error.
实例二:
package com.anno.test; import com.anno.test.FruitColor.Color; public class Fruit { @FruitName("Apple") private String appleName; @FruitColor(fruitColor=Color.RED) private String appleColor; @FruitProvider(id=1,name="陕西红富士集团",address="陕西省西安市延安路89号红富士大厦") private String appleProvider; public void setAppleColor(String appleColor) { this.appleColor = appleColor; } public String getAppleColor() { return appleColor; } public void setAppleName(String appleName) { this.appleName = appleName; } public String getAppleName() { return appleName; } public void displayName(){ System.out.println("水果的名字是:苹果"); } }
package com.anno.test; import java.lang.annotation.Target; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * 水果名称注解 */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface FruitName { String value() default ""; }
package com.anno.test; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface FruitColor { public enum Color{BULE,RED,GREEN} Color fruitColor() default Color.BULE; }
package com.anno.test; 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; @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface FruitProvider { /** * 供应商编号 * @return */ public int id() default -1; /** * 供应商名称 * @return */ public String name() default ""; /** * 供应商地址 * @return */ public String address() default ""; }
package com.anno.test; import java.lang.reflect.Field; public class FruitInfoUtil { public static void getFruitInfo(Class<?> clazz){ String strFruitName=" 水果名称:"; String strFruitColor=" 水果颜色:"; String strFruitProvicer="供应商信息:"; Field[] fields = clazz.getDeclaredFields(); for(Field field :fields){ if(field.isAnnotationPresent(FruitName.class)){ FruitName fruitName = (FruitName) field.getAnnotation(FruitName.class); strFruitName=strFruitName+fruitName.value(); System.out.println(strFruitName); } else if(field.isAnnotationPresent(FruitColor.class)){ FruitColor fruitColor= (FruitColor) field.getAnnotation(FruitColor.class); strFruitColor=strFruitColor+fruitColor.fruitColor().toString(); System.out.println(strFruitColor); } else if(field.isAnnotationPresent(FruitProvider.class)){ FruitProvider fruitProvider= (FruitProvider) field.getAnnotation(FruitProvider.class); strFruitProvicer=" 供应商编号:"+fruitProvider.id()+" 供应商名称:"+fruitProvider.name()+" 供应商地址:"+fruitProvider.address(); System.out.println(strFruitProvicer); } } } }
package com.anno.test; public class FruitRun { /** * @param args */ public static void main(String[] args) { FruitInfoUtil.getFruitInfo(Fruit.class); } }
输出结果:
水果名称:Apple
水果颜色:RED
供应商编号:1 供应商名称:陕西红富士集团 供应商地址:陕西省西安市延安路89号红富士大厦
实例三:
/** * */ package com.guxiang.test; 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; /** * * @date 2016年12月24日 下午10:22:11 * 自定义的myTest注解 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD,ElementType.ANNOTATION_TYPE}) public @interface MyTest { long time() default -1; }
package com.guxiang.test; public class SomeDaoImpl { public void save(){ System.out.println("保存了数据"); } public void update(){ System.out.println("更新了数据"); } }
package com.guxiang.test; public class SomeDaoImplTest { private SomeDaoImpl dao= new SomeDaoImpl(); /** * 测试添加 */ @MyTest public void testAdd(){ dao.save(); } @MyTest public void testUpdate(){ dao.update(); } }
/** * */ package com.guxiang.test; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * @author guxiang * @date 2016年12月24日 下午10:26:07 */ // 反射注解 public class MyTestRunner { public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException { Class clazz = SomeDaoImplTest.class; Method[] ms = clazz.getMethods(); for (Method method : ms) { boolean hasMyTest = method.isAnnotationPresent(MyTest.class); if (hasMyTest) { method.invoke(clazz.newInstance(), null); } } } }
输出:
保存了数据
更新了数据