W
W
woodhead2019-03-11 04:48:47
Java
woodhead, 2019-03-11 04:48:47

How to cast parameterized types on 'Unchecked assignment'?

How to properly type cast in the following function:

public static <T> Dao<T> getDao(Class<T> cl){
    for(Dao dao : daoList){
        if (cl == dao.getParameterizedClass())
            return dao;
    }
    return null;
}

The fact is that in the line the return daoword daois highlighted and a warning appears Unchecked assignment: 'dao.Dao' to 'dao.Dao<T>.
This is what the class containing this function looks like:
public abstract class DaoFactory {

    private static final List<Dao<?>> daoList = Arrays.asList(
            new DaoImpl<>(Person.class)    
    );

    public static <T> Dao<T> getDao(Class<T> cl){
        for(Dao dao : daoList){
            if (cl == dao.getParameterizedClass())
                return dao;
        }
        return null;
    }
}

And this is the interface Dao:
public interface Dao<T> {  
    Class<T> getParameterizedClass();
}

and its implementation:
public class DaoImpl<T> implements Dao<T> {

    private Class<T> parameterizedClass;

    DaoImpl(Class<T> cl){
        this.parameterizedClass = cl;
    }

    @Override
    public Class<T> getParameterizedClass() {
        return parameterizedClass;
    }
}

Of course, you can suppress the warning, or make the return type non-parameterized - not Dao<T>, but just Dao. Is there another way to resolve the warning?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question