java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType

后端 未结 2 1364
温柔的废话
温柔的废话 2021-01-13 05:53

I have created hierarchy of interface and classes using generic and messed up everything.
Topmost class is AbstractJpaEntity which is extended by all domain entity

相关标签:
2条回答
  • 2021-01-13 06:16

    This is a solution

    public TO getTo() throws Exception {
        if(to == null) {
            try {
                to = ((Class<TO>) ((ParameterizedType) this.getClass().getGenericSuperclass())
                        .getActualTypeArguments()[0]).newInstance();
            } catch(ClassCastException cce) {
                cce.printStackTrace();
                to = ((Class<TO>) ((ParameterizedType) (((Class<TO>) this.getClass()
                        .getAnnotatedSuperclass().getType()).getGenericSuperclass()))
                                .getActualTypeArguments()[0]).newInstance();
            }
        }
        return to;
    }
    
    0 讨论(0)
  • 2021-01-13 06:33

    In this class declaration

    public class ProductTypeDaoImpl extends GenericDaoImpl implements ProductTypeDao
    

    you're using GenericDaoImpl and ProductTypeDao as raw types. Start by reading why you shouldn't use them.

    The fact that you are using raw types causes problems here

    ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
    

    where getGenericSuperclass() will return a Class instance since GenericDaoImpl, in

    public class ProductTypeDaoImpl extends GenericDaoImpl implements ProductTypeDao
    

    is not parameterized and therefore isn't a ParameterizedType. The cast then fails.

    The solution is to parameterize the two types in your class declaration. It's not immediately obvious from your code what those type arguments should be, but GenericTypeDao should probably take ProductTypeDomain

    public class ProductTypeDaoImpl extends GenericDaoImpl<ProductTypeDomain> implements ProductTypeDao
    

    and your interface ProductTypeDao should probably be declared as

    public interface ProductTypeDao extends GenericDao<ProductTypeDomain> {
    
    0 讨论(0)
提交回复
热议问题