把枚举替换成注解 Enum替换成Annotation

随手记录下新鲜的Annotation知识,google官网说Enum类比普通静态常量要消耗2倍内存, 所以现在把枚举改成注解.官方说法如下


1:首先定义用到的静态常量

public class Constants {
    public static final String TYPE_A = "1";
    public static final String TYPE_B = "2";
    public static final String TYPE_C = "3";
    public static final int TYPEDES_A = 1;
    public static final int TYPEDES_B = 2;
    public static final int TYPEDES_C = 3;
}

2:定义限定类型的注解类(两个单独的类)

//String类型的注解 @StringDef() 
@StringDef({Constants.TYPE_A,Constants.TYPE_B,Constants.TYPE_C})
public @interface FieldMata {
}
//int类型的注解
@IntDef({Constants.TYPEDES_A,Constants.TYPEDES_B,Constants.TYPEDES_C})
public @interface TypeDes {
}

3:使用注解

public class DemoTest {

    //在需要限定的方法内的参数写上先前定义的限定值
    private void printType(@FieldMata String type) {
        System.out.println(type);
    }

    private void printType(@TypeDes int des) {
        System.out.println(des);
    }

    public static void main(String[] args) {
        DemoTest demoTest = new DemoTest();
	//在调用时只能传入注解中定义的值
        demoTest.printType(Constants.TYPE_A);
        demoTest.printType(Constants.TYPEDES_A);
    }
}
public class DemoTest {

    //在需要限定的方法内的参数写上先前定义的限定值
    private void printType(@FieldMata String type) {
        System.out.println(type);
    }

    private void printType(@TypeDes int des) {
        System.out.println(des);
    }

    public static void main(String[] args) {
        DemoTest demoTest = new DemoTest();
	//在调用时只能传入注解中定义的值
        demoTest.printType(Constants.TYPE_A);
        demoTest.printType(Constants.TYPEDES_A);
    }
}

4:另外

String类型的注解 @StringDef() 表示只能传入String类型的变量,{}表示只能是括号内的限定值:{Constants.TYPE_A,Constants.TYPE_B}(这些都是support:appcompat-v7中自带的,详情: http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2017/0330/7759.html




猜你喜欢

转载自blog.csdn.net/qq_35599978/article/details/79453564