vendredi 14 juillet 2017

Properly casting to unknown type passed as argument when no genericization is possible

I have a special types of enums which define a class, the class is then instanciable directly from an enum value. To achieve this each enum implement the following interface:

public interface IEnumWithClass {
    public Class<?> getAssociatedClass();
}

One enumeration would go like this:

public enum Foo implements IEnumWithClass {

    eEnumValue(Goo.class);

    private final Class<?>    mAssociatedClass;

    SolverArchitectures(Class<?> iAssociatedClass) {
        mAssociatedClass = iAssociatedClass;
    }

    @Override
    public Class<?> getAssociatedClass() {
        return mAssociatedClass;
    }
}

The class can then be instanciated using the following helper:

public class EnumWithClassHelper extends EnumWithValueHelper {
    private static Object getInstance(Class<?> type) throws Exception
    {    
        Constructor<?> constructor  = type.getConstructor();        
        return constructor.newInstance();
    }   
}

And a call like the following one:

Goo myGoo = (Goo) EnumWithClassHelper.getInstance( Foo.eEnumValue.getAssociatedClass() );

Problem: I'd like to avoid the cast here, and directly get a Goo.

I made it using the following helper:

@SuppressWarnings("unchecked")
private static <T> T getInstance(Class<?> type) throws Exception
{    
    Constructor<?> constructor  = type.getConstructor();        
    return (T) constructor.newInstance();
}

But in this case, I have an unchecked cast exception warning, which I do not want either.

Any way to do it safely or am I to stick with the first solution ? It seems that I cannot pass Class as an argument due to interface and enumeration limitations ( I did not succeed in specifying a generic argument to the enum ).

Thanks ! :)





Aucun commentaire:

Enregistrer un commentaire