views:

33

answers:

1

Hi all

How can I get the package name (in general, the class) of a generic type argument? I have a class similar to this:

public class MyClass<T> {}

What I'd like to do is something like this (non-working pseudo-Java):

return T.class.getPackage().getName();

I need this, since JAXB needs this as the context path (JAXBContext.newInstance(String) method). Of course I'm open to more elegant ways of working with JAXBContext. :)

Cheers Matthias

+4  A: 

This is a possible solution (if you can change MyClass):

public class MyClass<T> {

   private Class<T> clazz;
   public MyClass (Class<T> clazz) {
     this.clazz = clazz;
   }

   public String getPackageNameOfGenericClass() {
     return clazz.getPackage().getName(); 
   }

}
Andreas_D
Thank you! Looks nice, though it is slightly redundant. But it seems to be unavoidable...
Mudu