您的位置:首页 > 移动开发 > Android开发

在Android中如何使用注解取代Enum

2016-07-12 16:27 483 查看

在Android中如何使用注解取代Enum

Android中定义了许多的注解,如@IdRes,@LayoutRes…可以帮助我们在传递参数时,避免参数传递出错。当然我们也可以通过枚举定义参数,也可以达到相同效果。在Android中,系统为我们定义好了2个注解,@IntDef和@StringDef,具体代码如下所示:

Test类定义好注解

public class Test {

public static final int A = 0;
public static final int B = 1;
public static final int C = 2;
public static final int D = 3;
public static final String E = "E";
public static final String F = "F";
public static final String G = "G";
public static final String H = "H";

@IntDef({A, B, C, D})
@Retention(RetentionPolicy.SOURCE)
public @interface FormatInt {

}

@StringDef({E, F, G, H})
@Retention(RetentionPolicy.SOURCE)
public @interface FormatString {

}
}


public class MainActivity extends AppCompatActivity {

public class MainActivity extends AppCompatActivity {

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

int format = getInt(Test.A);

String f = getString(Test.E);

}

//在方法参数上使用注解
public int getInt(@Test.FormatInt int format) {
return format;
}

public String getString(@Test.FormatString String format) {
return format;
}
}


@IntDef注解的代码

@Retention(SOURCE)
@Target({ANNOTATION_TYPE})
public @interface IntDef {
/** Defines the allowed constants for this element */
long[] value() default {};

/** Defines whether the constants can be used as a flag, or just as an enum (the default) */
boolean flag() default false;
}


@StringDef的注解代码

@Retention(SOURCE)
@Target({ANNOTATION_TYPE})
public @interface StringDef {
/** Defines the allowed constants for this element */
String[] value() default {};
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: