-1

我创建了一个 HashMap,它将抽象模型的类作为键,然后将模型的实例作为值。我似乎无法添加它。Java 似乎不够聪明,无法意识到我放入 HashMap 的内容实际上是 Model 实例的子类。

abstract public class EntityManager<AbstractModel> {

    @Inject
    protected static Injector injector;

    private HashMap<Class<? extends AbstractModel>, AbstractModel> models = new HashMap<Class<? extends AbstractModel>, AbstractModel>();

    public void register(final AbstractModel model) {

        models.put(model.getClass(), model); // <-- the problem 

    }

    public AbstractModel get(Class<? extends AbstractModel> Class) {

        AbstractModel model = models.get(Class);

        if (model == null) {

            throw new RuntimeException("Attempting to retrieve an unregistered model.");

        } else {

            return model;
        }
    }
}

IntelliJ 告诉我它正在尝试添加Class<? extends Object>而不是Class<? extends Model>

4

3 回答 3

2

您在这里使用的.getClass()方法是Object. 它的文档说明了你应该在这里做什么:

final Class<? extends AbstractModel> c = model.getClass();
models.put(c, model);
于 2013-06-04T00:57:08.463 回答
0

您可以直接拨打电话:

models.put((Class<? extends AbstractModel>) model.getClass(), model);
于 2013-06-04T00:58:16.713 回答
0

感谢答案和建议,我最终选择了这个

abstract public class EntityManager<AbstractModel> {

    @Inject
    protected static Injector injector;

    private Map<Class<? extends AbstractModel>, AbstractModel> map = new IdentityHashMap<Class<? extends AbstractModel>, AbstractModel>();

    public EntityManager(){
        setUp();
    }

    public void register(Class<? extends AbstractModel> clazz) {

        map.put(clazz, injector.getInstance(clazz));
    }

    public AbstractModel get(Class<? extends AbstractModel> clazz) {

        AbstractModel model = map.get(clazz);

        if (model == null) {

            throw new RuntimeException("Attempting to retrieve an unregistered model.");

        } else {

            return model;
        }
    }

    abstract void setUp();
}
于 2013-06-04T01:07:31.470 回答