jeudi 23 novembre 2017

Factory pattern with generics in java

I'm having trouble implementing factory with generics for a specific use case

I have model classes:

class BaseModel { }

class ModelA extends BaseModel { }

class ModelB extends BaseModel { }

And corresponding services:

class Service<T extends BaseModel> { }

class ServiceA extends Service<ModelA> {}

class ServiceB extends Service<ModelB> {}

My Factory class, to create service according to the model it services:

class Factory {
    private Map<Class<? extends BaseModel>, Class<? extends Service>> registry;

    Factory(){
        registry = new HashMap<>();
        registry.put(ModelA.class, ServiceA.class);
        registry.put(ModelB.class, ServiceB.class);
    }

    Service getService(Class<? extends BaseModel> clazz) throws IllegalAccessException, InstantiationException {
        return registry.get(clazz).newInstance();
    }
}

And a class that uses the factory

class Handler<T extends BaseModel>{
    private Service<T> myService;

    Handler(Class<T> modelClass) {
        Factory fact = new Factory();
        try {
            myService = fact.getService(modelClass);
        } catch (IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
        }
    }
}

I get an warning for the line that uses the factory to get the service:

"Unchecked assignment 'Service' to 'Service<T>'"

I understand why I get the message, since the getService method returns Service, but I need Service<T> and puzzled about how I can change the code to get Service<T>

Any suggestions?

Thanks!

Aucun commentaire:

Enregistrer un commentaire