Final static string defined in interface not evaluated at compile time - Android

I have two classes and an interface (e.g. DatabaseModel , LocalStore and InternalModelInterface). They are defined as follows:

 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; // ... } 

The problem I am facing is that at runtime, when I call localStore.function() , temp is set to null and InternalModelInterface.COLUMN_PARAM1 is null. Does this make sense? Should I evaluate InternalModelInterface.COLUMN_PARAM1 at compile time and embed it?

This is an Android app. Thanks in advance.

I will explain further to clarify any confusion.

DatabaseModel objects are created when parsing a JSON response. The constants defined in the DatabaseModel class are the keys to look for in the JSON response.

InternalModelInterface defines the column names used in the local (cache) database on the device. For several reasons (including keys that are illegal column names in SQLite), I do not use keys as column names.

The reason I use the interface, and not just a simple class, is because the interface also specifies the necessary methods that must be implemented by the third LocalStore class.

+7
source share
2 answers

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 first initialized. This also applies to such fields in interfaces (§9.3.1). These variables are “constants” that will never be observed to their initial default values ​​(§4.12.5), even by crafty programs.

So null should never be observed in your example. This is an Android bug.

+3
source

I'm not an android expert, but I think that if you don't create an instance of the class, it will be optimized at compile time. If you create a constructor for DatabaseModel and create it somewhere, this seems to solve it for me.

0
source

All Articles