存储的类不应该是抽象类,ClassInstantiationException
因为类反射用于实例化检索到的记录。
这里有一个使用包装类发布的解决方法,但到目前为止我的方法是将“类”(在我的情况下为 serverType)存储为一个字段,并且在检索基类时将基类传递给所需子类的构造函数并复制它的属性。
用法
Dao<BaseConnectionInfo, Integer> connections = DatabaseManager
.getInstance(this).getDatabaseHelper()
.getDao(BaseConnectionInfo.class);
BaseConnectionInfo connection = connections.queryForId(1);
if (connection.isServerType(BaseConnectionInfo.SERVER_TYPE_MSSQL)) {
connection = new MsSqlConnectionInfo(connection);
} else if (connection
.isServerType(BaseConnectionInfo.SERVER_TYPE_MYSQL)) {
connection = new MySqlConnectionInfo(connection);
}
基本连接信息
@DatabaseTable(tableName = "connections")
public class BaseConnectionInfo implements SqlDriverInterface {
public static final String TAG = "BaseConnection";
public static final String SERVER_TYPE_MYSQL = "MYSQL";
public static final String SERVER_TYPE_MSSQL = "MSSQL";
public static final String SERVER_TYPE_SYBASE = "SYBASE";
public static final String SERVER_TYPE_POSTGRESQL = "POSTGRESQL";
@DatabaseField(generatedId = true)
private int id;
@DatabaseField
protected String serverType;
@DatabaseField
private String name;
...
public boolean isServerType(String serverType) {
return this.serverType.equals(serverType);
}
...
}
MySqlConnectionInfo
public class MySqlConnectionInfo extends BaseConnectionInfo {
public MySqlConnectionInfo() {
// FOR ORMLITE
serverType = SERVER_TYPE_MYSQL;
}
/**
* Constructor used to convert {@link BaseConnectionInfo} to
* {@link MySqlConnectionInfo}
*
* @param baseConnectionInfo
*/
public MySqlConnectionInfo(BaseConnectionInfo b) {
setId(b.getId());
setName(b.getName());
setHost(b.getHost());
setOptionsJson(b.getOptionsJson());
}
...
}
MsSqlConnectionInfo
public class MsSqlConnectionInfo extends BaseConnectionInfo {
public MsSqlConnectionInfo() {
// FOR ORMLITE
serverType = SERVER_TYPE_MSSQL;
}
/**
* Constructor used to convert {@link BaseConnectionInfo} to
* {@link MsSqlConnectionInfo}
*
* @param baseConnectionInfo
*/
public MsSqlConnectionInfo(BaseConnectionInfo b) {
setId(b.getId());
setName(b.getName());
setHost(b.getHost());
setOptionsJson(b.getOptionsJson());
}
...
}