我有两个类和一个接口(例如
DatabaseModel,LocalStore和InternalModelInterface).它们的定义如下;
public class DatabaseModel { // ... public static final String KEY_PARAM1 = "param1"; } public class LocalStore implements InternalModelInterface { // ... public void function () { String temp = InternalModelInterface.COLUMN_PARAM1; } } public interface InternalModelInterface { public static final String COLUMN_PARAM1 = DatabaseModel.KEY_PARAM1; // ... }
我遇到的问题是,在运行时,当我调用localStore.function()时,temp被赋值为null,因为InternalModelInterface.COLUMN_PARAM1为null.这有意义吗?是不是应该在编译时评估InternalModelInterface.COLUMN_PARAM1并内联?
这适用于Android应用程序.提前致谢.
我将进一步解释澄清任何混淆.
DatabaseModel类的对象在解析JSON响应时被实例化. DatabaseModel类中定义的常量表示在JSON响应中查找的键.
InternalModelInterface定义设备上本地(缓存)数据库中使用的列名称.由于多种原因(包括它们的键是sqlite中的非法列名),我不会将键重用为列名.
我使用接口而不仅仅是普通类的原因是接口还指定了需要由第三类LocalStore实现的必需方法.
解决方法
JLS3§8.3.2.1,§9.3.1
http://java.sun.com/docs/books/jls/third_edition/html/classes.html#38010
at run time,static variables that are
final and that are initialized with
compile-time constant values are
initialized first. This also applies
to such fields in interfaces (§9.3.1).
These variables are “constants” that
will never be observed to have their
default initial values (§4.12.5),even
by devIoUs programs.
因此,在您的示例中永远不应该观察到null.那是一个Android bug.