3

我有以下方法:

public static Category getImpl(Class<Category> category) throws IllegalAccessException, InstantiationException
{

        Reflections reflections = new Reflections("com.dpd.modules");
        Set<Class<? extends Category>> classes = reflections.getSubTypesOf(category);


        Category queryGetter = null;

        if (DDLTool.isOracle())
        {
            for (Class s : classes)
            {
                if (Oracle.class.isAssignableFrom(s))
                {
                    queryGetter =  s.newInstance();
                }
            }

        }
        else if (DDLTool.isMSSQL())
        {
            for (Class s : classes)
            {
                if (MsSql.class.isAssignableFrom(s))
                {
                    queryGetter = s.newInstance();
                }
            }
        }
        else if (DDLTool.isPostgres())
        {
            for (Class s : classes)
            {
                if (PosgtreSql.class.isAssignableFrom(s))
                {
                    queryGetter = s.newInstance();
                }
            }
        }

        return queryGetter;

 }

但是,我不能真正将 queryGetter 转换为所需的类别

继承树如下所示:

Category (Interface) -> PortalCorp extends Category (Interface) | Portal365 extends Category (Interface) 

Oracle | MsSql | PosgtreSql (all Interfaces)

然后是具体的类(仅适用于 PortalCorp,Portal365 也是如此):

MsSqlQueryGetterPortalCorp implements PortalCorp, MsSql

OracleQueryGetterPortalCorp implements PortalCorp, Oracle

PostgresQueryGetterPortalCorp implements PortalCorp, PosgtreSql

但是我在线上遇到不兼容的类型错误:

queryGetter = s.newInstance();

我如何以这样的方式实现所需的行为,如果我执行

 getImpl(PortalCorp.class); 

DDLTool.isOracle()返回真

我最终会得到com.dpd.modules.OracleQueryGetterPortalCorp?

提前致谢

4

1 回答 1

0

循环变量没有使用泛型。如果您尝试:

for (Class<? extends Category> s : classes)

如果编译器也不喜欢这样,那么在分配新实例之前如何转换它:

queryGetter = (Category) s.newInstance();
于 2020-05-04T07:13:22.960 回答