更新了问题:
我可以设计一个父类来访问子类静态成员而不会抛出错误吗?如果这是可能的,那怎么办呢?
基本上,我有一个扩展SQLiteOpenHelper的DbHelper类。我还实施了所需的必要方法。
public class DbHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDb.sqlite3";
public static final int DATABASE_VERSION = 1;
public static final String CREATE_TABLE_FOO = "CREATE TABLE " + FooAdapter.TABLE_NAME
+ " (" + FooAdapter.COLUMN_BAR + " INTEGER PRIMARY KEY)";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_FOO);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// do nothing
}
}
然后我将这个类扩展为更具体的子类FooAdapter
public class FooAdapter extends DbHelper {
public static String TABLE_NAME = "foo";
public static String COLUMN_BAR = "bar";
public FooAdapter(Context context) {
super(context);
}
// table specific methods, select, insert, delete
}
在评论的帮助下,我发现错误是因为DbHelper正在访问FooAdapter的静态成员,但FooAdapter是DbHelper的子类。
所以,如果我在一个活动中实例化FooAdapter,我会得到ExceptionInInitializerError。
FooAdapter fooDb = new FooAdapter(this); // throws ExceptionInInitializerError
但如果我首先实例化DbHelper,一切都运行良好。
DbHelper dbHelper = new DbHelper(this);
FooAdapter fooDb = new FooAdapter(this); // no error
我检查了logcat,最后一行错误是DbHelper.<clinit>(DbHelper.java...)