samedi 2 mai 2020

How do I dynamically cast Java object

I have the following method:

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;

 }

However, I can't really cast queryGetter to desired Category

The inheritance tree looks like this:

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

Oracle | MsSql | PosgtreSql (all Interfaces)

And then the concrete classes (only for PortalCorp, the same goes for Portal365) :

MsSqlQueryGetterPortalCorp implements PortalCorp, MsSql

OracleQueryGetterPortalCorp implements PortalCorp, Oracle

PostgresQueryGetterPortalCorp implements PortalCorp, PosgtreSql

But I get Incompatible Types error on the line:

queryGetter = s.newInstance();

How do I implement desired behaviour in such a way that if I execute

 getImpl(PortalCorp.class); 

and DDLTool.isOracle() returns true

I will finally get instance of com.dpd.modules.OracleQueryGetterPortalCorp?

Thanks in advance





Aucun commentaire:

Enregistrer un commentaire