Search code examples
javaclassgenericsobjectfactory

ObjectFactory with Class<?> argument


I'm developing a factory which can instantiate objects of type Ability by using Class parameter. The code for this factory is:

public static final class AbilityFactory {
    private AbilityFactory(){}

    public static <T extends Class<A>, A extends Ability> A getAbility(T clazz){
        A ability = null;
        try{
            ability = clazz.newInstance();
        } catch(InstantiationException | IllegalAccessException ex){
            ex.printStackTrace();
        }
        return ability;
    }
}

Client code is something like that:

Ability.AbilityFactory.getAbility(Firebolt.class));

The only problem I figured about this design is that Ability class is abstract and you can pass something like this:

Ability.AbilityFactory.getAbility(Ability.class)); 

which results in java.lang.InstantiationException.

I wanted to know whether I can make some constraints like "? extends Ability but not Ability" or it's just a bad design and I should pass, for example, Enum as an argument into factory's method to prevent this situation.


Solution

  • The only thing you could do is to provide a marker interface let's say ConcreteAbility and have <T extends Ability & ConcreteAbility>. Then you need to implement ConcreteAbility with all concrete abilities.