自定义注解

1.首先新建一个类

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String name();
}

@Retention 表示该注解的生命周期,可选的 RetentionPolicy 参数包括RetentionPolicy.SOURCE 注解将被编译器丢弃 
RetentionPolicy.CLASS 注解在class文件中可用,但会被VM丢弃 
RetentionPolicy.RUNTIME VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息
2.public class DraweeViewAnnotation {
    @MyAnnotation(name = "Hello world")
    public void execute(){
      System.out.println("method");
    }

}

3.如果想要获取name变量的值

需要通过反射

 DraweeViewAnnotation draweeViewAnnotation=new DraweeViewAnnotation();
        Class<DraweeViewAnnotation> c=DraweeViewAnnotation.class;
        try {
            
            Method method=c.getMethod("execute",new Class[]{});
            if(method.isAnnotationPresent(MyAnnotation.class)){
                MyAnnotation myAnnotation=method.getAnnotation(MyAnnotation.class);
                try {
                    //利用反射获取值
                    method.invoke(draweeViewAnnotation,new Object[]{});
                    mName = myAnnotation.name();
                    Toast.makeText(MainActivity.this, mName,Toast.LENGTH_SHORT).show();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值