Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

final static String defined in an interface not evaluated at compile time - Android

I have two classes and an interface (for example DatabaseModel, LocalStore, and InternalModelInterface). They're 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 issue I'm experiencing is that at runtime, when I call localStore.function(), temp is being assigned null, as InternalModelInterface.COLUMN_PARAM1 is null. Does this make sense? Shouldn't InternalModelInterface.COLUMN_PARAM1 be evaluated at compile time and inlined?

This is for an Android application. Thanks in advance.

I'll further explain to clarify any confusion.

Objects of the DatabaseModel class are instantiated as a JSON response is parsed. The constants defined in the DatabaseModel class represent the keys to look for in the JSON response.

The InternalModelInterface defines the column names used in the local (cache) database on the device. For several reasons (including they keys being illegal column names in SQLite), I'm not reusing the keys as column names.

The reason I'm using an interface and not just a plain class is that the interface also specifies required methods that need to be implemented by the third class, LocalStore.

like image 677
1in9ui5t Avatar asked May 19 '11 16:05

1in9ui5t


1 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 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.

So null should never be observed in your example. It's an Android bug then.

like image 52
irreputable Avatar answered Oct 23 '22 21:10

irreputable