在Android中使用接口到命名空间常量

时间:2011-04-14 03:48:41

标签: java android

从我所读到的使用接口来定义常量通常在Java中被忽略,除非你打算通过类继承常量来实现接口。但我经常在Android程序中遇到这样的代码:

interface Tags {
    String BLOCK = "block";
    String TITLE = "title";
    String START = "start";
    String END = "end";
    String TYPE = "type";
}

我个人喜欢能够像这样将常量组合成一个命名空间。所以我的问题是这样做有什么不利之处吗?我假设它可能不如使用静态最终字符串那样高效,因为编译器可以内联它们。

1 个答案:

答案 0 :(得分:7)

首先,要知道界面中的字段是隐含的静态和最终的。

常量接口通常被视为反模式(请参阅http://en.wikipedia.org/wiki/Constant_interface)。更好的选择是:

public final class Tags {
    public static final String BLOCK = "block";
    // Other constants...

    private Tags() {}
}

由于Tags类是final,所以没有类可以扩展它。相反,想要使用来自Tags的常量的类只需:

import my.package.Tags;

然后:

System.out.println(Tags.BLOCK);

从Java 5开始,可以直接导入常量:

import static my.package.Tags.BLOCK;
// Other static imports...

所以他们可以像这样使用:

System.out.println(BLOCK);