I am trying to create a service container and want to know how to reflect the type used when calling the method. See below:
public class ServiceContainer {
HashMap<Type, Object> services;
public ServiceContainer() {
services = new HashMap<Type, Object>();
}
public <T> void addService(Type t, T object) {
services.put(t, object);
}
public <T> void addService(T object) {
Type type = typeof(T);
services.put(type, object);
}
}
I would prefer to use the second addService, but if this is not possible, then something will disappear.
EDIT: I think I found a solution for addService, but now there is another method that cannot be resolved in the same way:
public class ServiceContainer {
HashMap<Class, Object> services;
public ServiceContainer() {
services = new HashMap<Class, Object>();
}
public <T> void addObject(T object) {
Class type = object.getClass();
services.put(type, object);
}
public <T> boolean containsService() {
}
public <T> T getService() {
services.get(
ServiceContainer.class.getMethod( "getService", null )
.getGenericParameterTypes()[0] );
}
}
Now I’m kind of shooting into the dark, I have to comb the documentation ...
source
share