超简单自定义注解传值

本文介绍了两种通过自定义注解在Android中传递值的方法,包括在MainActivity中使用注解,以及创建DraweeViewAnnotation并获取注解值的详细步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

两种方法

第一种
1.自定义注解类


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnotation {
    String value();
}

2.MainActivity


public class MainActivity extends AppCompatActivity {

    private StudentBean studentBean;
    private Class<? extends StudentBean> aClass;

   @MyAnnotation("ZHUHUOHUO")
    String mStr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        自定义注解传值
        MainActivity activity = new MainActivity();
        Class<? extends MainActivity> aClass = activity.getClass();
        Field[] fields = aClass.getDeclaredFields();
        for (Field f:fields ) {
            MyAnnotation annotation = f.getAnnotation(MyAnnotation.class);
            if(annotation!=null){
                String value = annotation.value();
                Toast.makeText(this, value, Toast.LENGTH_SHORT).show();
            }
        }
    }
}

第二种
1.自定义注解类

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

2.自定义注解类DraweeViewAnnotation

public class DraweeViewAnnotation {
    @MyNotation(name="Hello world")
    public void getValue(){  }
}

3.得到注解的值(点击事件)

 TwoDraweeViewAnnotation twoDraweeViewAnnotation = new TwoDraweeViewAnnotation();
	  Class<TwoDraweeViewAnnotation> twoClas = TwoDraweeViewAnnotation.class;
	   try {
	       Method method = twoClas.getMethod("value", new Class[]{});
	       if (method.isAnnotationPresent(TwoNotation.class)){
	           method.getAnnotation(TwoNotation.class);
	           method.invoke(twoDraweeViewAnnotation,new Object[]{});
	           Toast.makeText(this, method.getName(), Toast.LENGTH_SHORT).show();
	       }
	   } catch (Exception e) {
	       e.printStackTrace();
	   }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值