0

Possible Duplicate:
How to determine the class of a generic type?
How to obtain class instance generic argument type

I have some c# code:

public static class ServiceLocator
{ 

   private static Dictionary<Type, Type> services = new Dictionary<Type, Type>();

   public static void RegisterService<T>(Type service)
   {
      services[typeof (T)] = service;
   } 

...

}

I want to write the same logic on java. How can I get type of generic T (T.getClass() not working) like typeof (T) in c#?

Community
  • 1
  • 1
Sergey Gazaryan
  • 1,013
  • 1
  • 9
  • 25
  • 2
    Duplicate of any of several: http://stackoverflow.com/questions/182636/how-to-determine-the-class-of-a-generic-type, http://stackoverflow.com/questions/1353901/is-there-a-way-to-find-the-type-of-a-template-generic-parameter-in-java, http://stackoverflow.com/questions/1372432/how-to-obtain-class-instance-generic-argument-type, ... – T.J. Crowder Nov 16 '11 at 13:28

2 Answers2

2

You can't. Generics are erased after compilation. You have to pass Class<T> as argument.

I don't quite understand your example, though. Why would you want to map a Type (Class) to itself?

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • As you can use as "service" a subclass of Type, the result would be different. – Matteo Nov 16 '11 at 13:29
  • It's something like IoC Container which registers one type for another and can be retrieved by registered key. – Sergey Gazaryan Nov 16 '11 at 13:34
  • No itself , I wont write something like ServiceLocator.RegisterService(typeof(ReportBuilder)) and after call ServiceLocator.Resolve() that will return instance of ReportBuilder – Sergey Gazaryan Nov 16 '11 at 13:36
0

It is not advisable, But you can check isAssignableFrom(Class cls) for all the Classes you expect it to be, but It's sounds like a better design can be implemented here (one that doesn't involve type checking)

Ido.Co
  • 5,317
  • 6
  • 39
  • 64