关于java注释,修饰--方法

来源:互联网 发布:淘宝客 2016 qq空间 编辑:程序博客网 时间:2024/06/05 08:28
  1. 先自定义一个注释类
@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface AnnotationMine{    byte cid() default -1;}

@Target 解释为限定本注释类所修饰的目标的类型
@Retention 本意为维持,保持,这里解释为此注释的适用范围

    2. 用法

@AnnotationMine(cid = Sdk_define.CID_DEMAND_COLLECT)    public void handleAddDemandCollect(RspParam param)    {            }
protected final void invokeMethod(RspParam param)    {        int cid = param.getCid();        Class cl = this.getClass();        for (Method method : cl.getDeclaredMethods())        {            AnnotationMine oc = method.getAnnotation(AnnotationMine.class);            if (oc != null)            {                int id = oc.cid();                if (cid == id)                    try                    {                        method.setAccessible(true);                        method.invoke(this, param);                    }                    catch (IllegalAccessException e)                    {                        e.printStackTrace();                        LogUtil.e("catch",e);                    }                    catch (InvocationTargetException e)                    {                        e.printStackTrace();                        LogUtil.e("catch",e);                    }            }        }    }

a这里用到反射机制,先取出当前类中额method,开始遍历,
b.用getAnnotation取出关于这个method的注释,
c.加入一个null检查(因为测试类中并不是所有的方法都用了@AnnotationMine修饰,会存在空现象)
d.调用注释的cid方法,得到cid
e.用上一步得到的cid匹配得到目标method
f.method.invoke调用起来,第一参数解释为这个方法的所属类,后面参数解释为method的参数
@param receiver  the object the underlying method is invoked from
0 0