使用API16,在Androids SQLiteDatabase类中引入了新的WAL(Write Ahead Logging)。我想测试是否为SQLite数据库启用了WAL。该应用程序也在较旧的Android版本上运行,因此我需要在SQLiteDatabase中为这些新函数提供包装类。功能是:
在Android Developer Blog我找到了一篇包装新类的包装类的文章。我没有找到的是现有类中新方法的包装器。我该怎么做?
答案 0 :(得分:1)
SQLiteDatabase
的构造函数是私有的,因此您无法扩展它并为类本身添加“包装器”。但是你可以像这样编写一个“帮助器”包装器:
public class WALWrapper {
private boolean mAvailable;
private Method mIsWriteAheadLoggingEnabled;
private Method mEnableWriteAheadLogging;
private Method mDisableWriteAheadLogging;
private final SQLiteDatabase mDb;
public WALWrapper(SQLiteDatabase db) {
mDb = db;
mAvailable = false;
try {
mIsWriteAheadLoggingEnabled =
SQLiteDatabase.class.getMethod("isWriteAheadLoggingEnabled");
mEnableWriteAheadLogging =
SQLiteDatabase.class.getMethod("enableWriteAheadLogging");
mDisableWriteAheadLogging =
SQLiteDatabase.class.getMethod("disableWriteAheadLogging");
mAvailable = true;
} catch (NoSuchMethodException e) {
}
}
/**
* Returns <code>true</code> if the {@link #isWriteAheadLoggingEnabled()},
* {@link #enableWriteAheadLogging()} and {@link #disableWriteAheadLogging()}
* are available.
* @return <code>true</code> if the WALWrapper is functional, <code>false</code>
* otherwise.
*/
public boolean isWALAvailable() {
return mAvailable;
}
public boolean isWriteAheadLoggingEnabled() {
boolean result = false;
if (mIsWriteAheadLoggingEnabled != null) {
try {
result = (Boolean) mIsWriteAheadLoggingEnabled.invoke(mDb);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
return result;
}
public boolean enableWriteAheadLogging() {
boolean result = false;
if (mEnableWriteAheadLogging != null) {
try {
result = (Boolean) mEnableWriteAheadLogging.invoke(mDb);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
return result;
}
public void disableWriteAheadLogging() {
if (mDisableWriteAheadLogging != null) {
try {
mDisableWriteAheadLogging.invoke(mDb);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
}
}