使用注解限定入参

2021-11-25  本文已影响0人  笨鱼天阳

时间长了总是会容易遗忘的知识点

前言

其实这个写不写都能从源码里翻例子,但是每次去翻总觉得找的不是自己想要的,算了,还是写一下记录下吧。

    @Retention(SOURCE)
    @StringDef({
       POWER_SERVICE,
       WINDOW_SERVICE,
       LAYOUT_INFLATER_SERVICE
    })
    public @interface ServiceName {}
    public static final String POWER_SERVICE = "power";
    public static final String WINDOW_SERVICE = "window";
    public static final String LAYOUT_INFLATER_SERVICE = "layout_inflater";
    ...
    public abstract Object getSystemService(@ServiceName String name);
    @Retention(SOURCE)
    @IntDef({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS})
    public @interface NavigationMode {}
    public static final int NAVIGATION_MODE_STANDARD = 0;
    public static final int NAVIGATION_MODE_LIST = 1;
    public static final int NAVIGATION_MODE_TABS = 2;
    ...
    public abstract void setNavigationMode(@NavigationMode int mode);
    @NavigationMode
    public abstract int getNavigationMode();

    // For a flag, set the flag attribute:
    @IntDef(
        flag = true,
        value = {NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS})

    @IntRange(from=0,to=255)
    public int getAlpha() {
        ...
    }

其它

其它的还有很多的,不一一列举了,可以参考官网文档,或者直接去看源码去。

参考

https://developer.android.google.cn/reference/android/support/annotation/IntDef
https://developer.android.google.cn/reference/android/support/annotation/StringDef
https://developer.android.google.cn/reference/android/support/annotation/IntRange

上一篇下一篇

猜你喜欢

热点阅读