m.tariqsiddiqui
m.tariqsiddiqui

Reputation: 27

Cannot instantiate the type in Generics

I am using Apache common dbutils for handling my database related operations, for my front end I am using Dojo for which I want ArrayList for different POJO classes instead of simple ResultSet. Below is my current method and I have several methods like this, I want to implement Gnerics so that I can remove this repetition from the code. I tried to implement Generics but it is failing at new BeanListHandler<?>(?.class); point and I am getting

Cannot instantiate the type BeanListHandler<?>

Kindly help me to resolve this issue as I am a returning Java programmer after a long time and I need your help guys, I shall be very thankful, also thanks in advance.

Here is my working code

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)
    {}
}

This is my failed Generic conversion

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)
    {}
}   

Upvotes: 0

Views: 915

Answers (1)

Ozan
Ozan

Reputation: 4415

You have to use a generic type parameter instead of ?:

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

Upvotes: 1

Related Questions