无法在泛型中实例化类型

时间:2014-03-16 14:53:22

标签: java generics

我正在使用Apache common dbutils来处理我的数据库相关操作,对于我的前端我使用Dojo,我希望ArrayList用于不同的POJO类而不是简单的ResultSet。下面是我当前的方法,我有几个像这样的方法,我想实现Gnerics,以便我可以从代码中删除这个重复。我试图实现泛型但它在new BeanListHandler<?>(?.class);点失败并且我得到了

Cannot instantiate the type BeanListHandler<?>

请帮助我解决这个问题,因为我很长一段时间后都是一名退休的Java程序员,我需要你的帮助,我会非常感激,也要提前感谢。

这是我的工作代码

public List<DigitalCertificate> listValidCertificates()
{
    final String methodName = "listValidCertificates";
    logger.entering(CLASS_NAME, methodName);

    try
    {
        QueryRunner run = new QueryRunner(getDataSource());
        ResultSetHandler<List<DigitalCertificate>> rsHandler = new BeanListHandler<DigitalCertificate>(DigitalCertificate.class);
        List<DigitalCertificate> certificates = run.query(SQL_VALID_CERTIFICATES, rsHandler);

        if (logger.isLoggable(Level.FINER))
        {
            logger.logp(Level.FINER, CLASS_NAME, methodName, "run.query : executed.");
            logger.logp(Level.FINER, CLASS_NAME, methodName, "SQL Statement is " + SQL_VALID_CERTIFICATES);
        }

        logger.exiting(CLASS_NAME, methodName);
        return certificates;
    }
    catch (Exception e)
    {}
}

这是我失败的通用转换

public List<?> runQuerySQLToGetList(String SQL, Object[] params)
{
    final String methodName = "runQuerySQLToGetList";
    Object methodParams [] = {SQL, params} ; 
    logger.entering(CLASS_NAME, methodName, params);

    try
    {
        QueryRunner run = new QueryRunner(getDataSource());
        ResultSetHandler<List<?>> rsHandler = new BeanListHandler<?>(?.class);

        List<?> certificates = run.query(SQL, rsHandler);

        if (logger.isLoggable(Level.FINER))
        {
            logger.logp(Level.FINER, CLASS_NAME, methodName, "run.query : executed.");
            logger.logp(Level.FINER, CLASS_NAME, methodName, "SQL Statement is " + SQL);
        }

        logger.exiting(CLASS_NAME, methodName);
        return certificates;
    }
    catch (Exception e)
    {}
}   

1 个答案:

答案 0 :(得分:0)

您必须使用通用类型参数而不是?

public <T> List<T> runQuerySQLToGetList(String SQL, Object[] params, Class<T> clazz) {
...
    ResultSetHandler<List<T>> rsHandler = new BeanListHandler<T>(clazz);
...
}