Java - reflection to get a generic type of method

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 ...

+3
source share
1 answer

The second addService is not possible if you did not specify the class name (instead Type) - for example,

public class ServiceContainer {
 HashMap<Class, Object> services;

 public ServiceContainer() {
     services = new HashMap<Class, Object>();
 }

 public <T> void addService(Class<T>, T object) {
     services.put(t, object);
 }
 public <T> void addService(T object) {
     Class type = object.getClass();
     services.put(type, object);
 }
}

typeOfT() , java "" . " ", ocmpiler .

edit: : containsService:

public boolean containsService(String classname) {
   return services.get(Class.forName(classname)) != null;
}

, , , , , , . Spring google Guice,

+5

All Articles