开发者

Get Package Name of Generic Type Argument

开发者 https://www.devze.com 2023-01-06 20:48 出处:网络
How can I get the package name (in general, the class) of a generic type argument? I have a class similar to this:

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, s开发者_开发问答ince JAXB needs this as the context path (JAXBContext.newInstance(String) method). Of course I'm open to more elegant ways of working with JAXBContext.


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

}
0

精彩评论

暂无评论...
验证码 换一张
取 消