标签:动态性 ntb 字段 div tst its this mitm mit
//final修饰符
public final class Constants {
//私有构造方法
private Constants() {}
public static final int ConstantA = 100;
public static final int ConstantB = 100;
......
}
采用“类.常量名”方法进行调用。需要私有化构造方法,避免创建该类的实例。同时不需让其他类继承该类。
如果多处需要访问工具类中定义的常量,可以通过静态导入(static import)机制,避免用类名来修饰常量名。
public interface Constants {
int ConstantA = 100;
int ConstantB = 100;
......
}
在interface中声明的字段,虚拟机在编译时自动加上public static final修饰符。使用方法一般是“接口.常量名”。也可以通过实现该接口,直接访问常量名,即常量接口模式。
常量接口:即接口中不包含任何方法,只包含静态的final域,每个域都导出一个常量。使用这些常量的类实现这个接口,以避免用类名来修饰常量名。
常量接口模式是对接口的不良使用。具体参考如下:
The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class‘s exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.
There are several constant interfaces in the java platform libraries, such as java.io.ObjectStreamConstants. These interfaces should be regarded as anomalies and should not be emulated.
上述两种方法对比,interface中定义常量方法生成的class文件比第一种方法的class文件更小, 且代码更简洁, 效率更高.
但是在java中会产生问题,主要是java的动态性,java中一些字段的引用可以在运行期动态进行。某些场景下,部分内容改变可只进行部分编译。具体例子参考文档Java Interface 是常量存放的最佳地点吗?
该文推荐使用Class定义常量,但采用private修饰符,通过get方法获取常量。这种方案可以保证java的动态性。
public class A{
private static final String name = "bright";
public static String getName(){
return name;
}
参考:
https://www.ibm.com/developerworks/cn/java/l-java-interface/index.html
https://www.jianshu.com/p/0affad4762ef
Java中定义常量方法及建议(Class/Interface)
标签:动态性 ntb 字段 div tst its this mitm mit
原文地址:https://www.cnblogs.com/wanqieddy/p/9051568.html