Class定义常量
public class Constant {
public static final int SUNDAY = 0 ;
public static final int MONDAY = 1 ;
public static final int TUESDAY = 2 ;
public static final int WEDNESDAY = 3 ;
public static final int THURSDAY = 4 ;
public static final int FRIDAY = 5 ;
public static final int SATURDAY = 6 ;
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate ( Bundle savedInstanceState) {
super . onCreate ( savedInstanceState) ;
setContentView ( R . layout. activity_main) ;
printDay ( Constant . FRIDAY) ;
}
private void printDay ( int value) {
System . out. println ( value) ;
}
}
Enum定义常量
public class Constant {
public enum WeekDays {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate ( Bundle savedInstanceState) {
super . onCreate ( savedInstanceState) ;
setContentView ( R . layout. activity_main) ;
printDay ( Constant. WeekDays . FRIDAY) ;
}
private void printDay ( Constant. WeekDays value) {
System . out. println ( value) ;
}
}
Annotation定义常量
public class Constant {
@IntDef ( {
WeekDays . SUNDAY,
WeekDays . MONDAY,
WeekDays . TUESDAY,
WeekDays . WEDNESDAY,
WeekDays . THURSDAY,
WeekDays . FRIDAY,
WeekDays . SATURDAY
} )
@Retention ( RetentionPolicy . SOURCE)
public @interface WeekDays {
int SUNDAY = 0 ;
int MONDAY = 1 ;
int TUESDAY = 2 ;
int WEDNESDAY = 3 ;
int THURSDAY = 4 ;
int FRIDAY = 5 ;
int SATURDAY = 6 ;
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate ( Bundle savedInstanceState) {
super . onCreate ( savedInstanceState) ;
setContentView ( R . layout. activity_main) ;
printDay ( Constant. WeekDays . FRIDAY) ;
}
private void printDay ( @Constant.WeekDays int value) {
System . out. println ( value) ;
}
}
对比
Enum定义常量相对于Class定义常量能够将常量进行分组; Annotation定义常量相比于Enum定义常量不仅可以通过@Retention注解使得注解在源文件有效,不参与编译消耗内存空间而且通过Android中的@IntDef注解还可做入参非法输入值的校验。
Tip
switch下使用@IntDef注解的tip