简体   繁体   中英

Get Package Name of Generic Type Argument

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

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(); 
   }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM