【问题标题】:Invalid inferred types无效的推断类型
【发布时间】:2014-05-23 11:21:45
【问题描述】:

我只是想在数据库(ORMLite API)上编写一些通用帮助程序,我使用 Maven 编译它,编译过程失败

invalid inferred types for D; inferred type does not conform to declared bound(s)
[ERROR] inferred: com.j256.ormlite.dao.RuntimeExceptionDao<T,U>
[ERROR] bound(s): com.j256.ormlite.dao.RuntimeExceptionDao<capture#2 of ?,?>

我尝试使用 JDK 1.6 和 1.7 构建它。

public class BaseDbHelper<T,U> extends DatabaseHelper<T, U> {

    private Dao<T, U> dao = null;
    private RuntimeExceptionDao<T, U> runtimeDao = null;
    Class<?> entityClass;

    public BaseDbHelper(Context context) {
        super(context);
        entityClass = (Class<?>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    @Override
    public Dao<T, U> getDao() throws SQLException {
        if (dao == null) {
            // !!! ERROR
            dao = getDao(entityClass);
        }
        return dao;
    }

    @Override
    public RuntimeExceptionDao<T, U> getDataDao() {
        if (runtimeDao == null) {
            // !!! ERROR
            runtimeDao = getRuntimeExceptionDao(entityClass);
        }
        return runtimeDao;
    }

}

这里是标有错误的行中两个父类的签名

public <D extends com.j256.ormlite.dao.RuntimeExceptionDao<T,?>, T>  D getRuntimeExceptionDao(java.lang.Class<T> clazz) { }

public <D extends com.j256.ormlite.dao.Dao<T,?>, T>  D getDao(java.lang.Class<T> clazz) throws java.sql.SQLException { }

【问题讨论】:

  • entityClassClass&lt;?&gt; 类型,daoDao&lt;T, U&gt; 类型,所以 getDao 的结果将是 Dao&lt;?,?&gt; 类型,这显然与 Dao&lt;T, U&gt; 不一致, 因为编译器根本不知道? 代表哪种类型。

标签: java generics ormlite


【解决方案1】:

在这种情况下,您可能需要使用 TypeTools 之类的东西来解析类型参数:

public BaseDbHelper() {
  entityClass = TypeResolver.resolveRawArguments(BaseDbHelper.class, getClass())[0];
}

注意:这仅在 BaseDbHelper 被子类化以便T 的值可以在类型定义中捕获时才有效:

public BasePersonHelper extends BaseDbHelper<Person, PersonDAO> {}

否则T 的值将无法在运行时检索。

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-03
    相关资源
    最近更新 更多