-->

Dynamic values are not supported as attributes in

2020-07-27 04:20发布

问题:

I am using custom annotation to log the id which user clicked. But I am getting a error "Attribute value must be a constant". My code snippet is below.

mAssetId= Asset.getContentId();

  @TrackEvent("track_event")
    @ArrayParams({@Params(key = "content_id",value = mAssetId)})
    protected void attributeMethod() {
    }

Thanks in advance. Is there any way to pass dynamic values in annotation rather than static variables or constants. I am using AspectJ library for android.

回答1:

It's not possible to specify runtime values in annotation attributes, only constants, and even the set of possible types is limited to a few types:

primitives, String, Class, enums, annotations, and arrays of the preceding types

according to the Java 5 Language Guide - Annotations.



回答2:

yes that's right, I found a solution for logging run time values using annotation.Also i made slight change in anootation to support this

 @TrackEvent("track_event")
    protected void attributeMethod(@Params("id") String value) {
    }

In my case it worked, hope anyone can help this.



回答3:

In aspectj native syntax you may catch any runtime variables you need:

pointcut rtVar(int id): set(* int SomeClass.mAssetId) && args(id) && within(SomeClass);

And then proceed this id variable into joinpoint.