waqaslam
waqaslam

Reputation: 68187

Enforce android annotations at compile/runtime

I'm having a very simple class as an example below:

public class Demo {
    private int val;

    public int getVal() {
        return val;
    }

    public void setVal(@IntRange(from = 1, to = 10) int v) {
        val = v;
    }
}

Here, I'm enforcing a range on val using IntRange. This works fine when I create a new object and try to set a value out of range in my code. For example:

Demo d = new Demo();
d.setVal(500);  //android studio highlights this as lint-warning

However, I would like to enforce this range verification at compile and runtime and expect an error thrown when the value is not in range.

How can I achieve this?

P.S. I know I can check range within setVal method before updating my variable, but this is not I'm looking after and would like a solution through android's annotation library.

Upvotes: 3

Views: 382

Answers (1)

TarasAntoshchuk
TarasAntoshchuk

Reputation: 341

To enforce this annotation at compile time for release builds add lint.xml file with following content to the root of your module

<lint>
    <issue id="Range" severity="fatal"/> 
</lint>

By doing this, you override severity of "Range" lint warning and release build will fail if this warning occurs

It may be possible to implement mechanism that will enforce this annotation at runtime (e.g. using custom annotation processor), but that's much more complicated and doesn't worth the effort

Implementation via annotation processing might work like this:

Initial class with @IntRange annotation

public class Demo {
    private int val;

    public int getVal() {
        return val;
    }

    public void setVal(@IntRange(from = 1, to = 10) int v) {
        val = v;
    }
}

You can implement annotation processor to generate following class from your initial Demo class
(generated at compile time)

public class DemoWithChecks extends Demo {
    public void setVal(int v) {
        if (v >= 1 && v <= 10) {
            super.setVal(v)
        } else {
            //value out of range - throw exception or whatever
        }
    }
}

Then you can use DemoWithChecks instead of Demo in your code to enforce annotation checks at runtime.

P.S. Good article on writing your own annotation processors here

Upvotes: 1

Related Questions