0

我有

public class Entity

在哪个工作班上:

public class Table<Target extends Entity>
{
    public boolean save (Target target)
    public Target load (int id)
}

直到我将 Table 类的这个对象放在数据库类 Map 中,一切都很好,但是:

public class Database
{
    public String name;
    public Map<String, Table<? extends Entity>> tables = new HashMap <String, Table<? extends Entity>> ();
    public Context context;
    public int version;
    public Database (Context context, int version)
    {
        this.context = context;
        this.version = version;
    }
    public void add (Table<? extends Entity> table)
    {
        tables.put(table.name, table);
    }
    public Table <? extends Entity> table (String name)
    {
        return (Table<? extends Entity>) tables.get(name);
    }

}

假设我们有:

 public class Apple extends Entity

我希望这段代码能够工作:

    //init      
    database = new Database(getBaseContext(), 4);
    new Table<Apple> (database, Apple.class);

    //this is where solution need occurs !
    database.table("apples").save (new Apple("green apple"));

类型 Table(capture#1-of ? extends Entity) 中的方法 save(capture#1-of ? extends Entity) 不适用于参数(注)

如何使 map.get 方法起作用?

4

2 回答 2

1

为了使这更方便,您可以做的一件事是按目标类映射表:

Map<Class<? extends Entity>, Table<? extends Entity>> tables;

public void <T extends Entity> addTable(Class<T> cls, Table<T> table) {
    tables.put(cls, table);
    // alternately make it possible to get the target class from the table
}

@SuppressWarnings("unchecked")
public <T extends Entity> Table<T> getTable(Class<T> cls) {
    return (Table<T>) tables.get(cls);
}

正如注释所暗示的那样,这根本不是类型安全的——你需要确保你永远不会不匹配tables.

于 2012-11-11T13:25:44.053 回答
0

感谢用户millimoose,我修改了数据库类:

public class Database
{
    public String name;
    public Map<Class<? extends Entity>, Table<? extends Entity>> tables = new HashMap <Class<? extends Entity>, Table<? extends Entity>> ();
    public Context context;
    public int version;
    public Database (Context context, String name, int version)
    {
        this.name = name;
        this.context = context;
        this.version = version;
    }

    public <Target extends Entity> void add (Class<Target> target, Table<Target> table) 
    {
        tables.put(target, table);
    }   

    @SuppressWarnings("unchecked")
    public <Target extends Entity> Table<Target> table (Class<Target> target) 
    {
        return (Table<Target>) tables.get (target);
    }   
}

之后就可以像这样使用它:

    database = new Database(getBaseContext(),"notes", 1);
    database.add (Note.class, new Table<Note> (database, Note.class));


    database.table(Note.class).save (new Note("first note"));
    database.table(Note.class).save (new Note("second note"));
    database.table(Note.class).save (new Note("best note"));

    items.addAll(database.table(Note.class).load());    

似乎我还没有足够的技能知道它为什么起作用,但是在映射键中添加 (Class(? extends Entity) 解决了问题。

于 2012-11-11T17:46:01.713 回答