我有一个代表数据库记录的抽象 Record 类,它有两个抽象方法:getTable() 和 getColumns()。然后,我有一个扩展 Record 的 Customer 类,并在该类中实现这些抽象方法。
我试图弄清楚如何获取所有客户的列表,但尽可能保持该方法的可重用性,因此我更喜欢 getAllRecords(Record record) 方法而不是 getAllCustomers() 方法。
这是我迄今为止所拥有的。我无法创建新的 Record() 对象,因为它是抽象的,需要创建传入的类的实例。
//i'd like to do something like this to get all of the Customers in the db
// datasource.getAllRecords(new Customer());
public List<Record> getAllRecords(Record record) {
List<Record> records = new ArrayList<Record>();
Cursor cursor = database.query(record.getTable(),
record.getColumns(), null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Record record = cursorToRecord(cursor, record);
records.add(record);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return records;
}
private Record cursorToRecord(Cursor cursor, Record record) {
Record record = new Record(); <-- somehow clone a new instance of the record that was passed in
record.setId(cursor.getLong(0));
record.setValue("aKey",cursor.getString(1));
return record;
}
使用某种 RecordRegistry 对象代替为 Record 的每个子类使用单独的工厂类是否有意义?
class RecordRegistry{
private static final List<Record> RECORDS;
static {
final List<Record> records = new ArrayList<Record>();
records.add(new Customer());
records.add(new Company());
RECORDS = Collections.unmodifiableList(records);
}
public List<Record> allRecords(){
return RECORDS;
}
public Record buildRecord(Class cClass){
String className = cClass.getName().toString();
if(className.equalsIgnoreCase("customer")){
return new Customer();
}else if(className.equalsIgnoreCase("company")){
return new Company();
}
return null;
}
}
最佳答案
您可以获得 Record
的类,前提是 Record
的所有子类都具有无参数构造函数。
Record newRecord = record.getClass().newInstance();
请注意,您可以只传递类而不是对象本身。
您还可以传递一个工厂,该工厂将负责实例化正确的类。
interface RecordFactory {
Record create();
}
class CustomerFactory implements RecordFactory {
Record create() {
return new Customer();
}
}
public List<Record> getAllRecords(RecordFactory factory) {
...
for(...) {
...
Record record = factory.create();
...
}
...
}
关于java - 从抽象类创建对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16105753/