mardi 28 août 2018

Java di module with help of generics and reflection

I want to build my own simple di module, for that purpose I created:

public interface Factory<T> {
T getInstance();
}

and

public class DiImpl implments Di{

private Map<Class, Factory> map = new HashMap<>();

@Override
public <T> Factory<T> getFactory(Class<T> type) {
    return (Factory<T>) map.get(type);
}

@Override
public <T> void bind(Class<T> base, Class<? extends T> impl) {
    map.put(base, new Factory<Class<?>>() {
        @Override
        public Class getInstance() {
            return impl;
        }
    });
}
}

But this code not pass simple test:

interface SimpleService {
....
}

FirstVaraintService implements SimpleService {
...
}

@Test
void test(){
Di di= new DiImpl();
di.bind(SimpleService.class, FirstVaraintService.class);       
Factory<SimpleService> factory = di.getFactory(SimpleService.class);
assertSame(FirstVaraintService.class, factory.getInstance().getClass());
}

compiler returns:

java.lang.ClassCastException: java.lang.Class cannot be cast to ... SimpleService

I know that, such di structure can be implemented with help of reflection API, but I don't know how to properly use it in this example. Please help me to change my code to pass the test.





Aucun commentaire:

Enregistrer un commentaire