Get “Class” object from generic type T

后端 未结 6 1713

I want to make generic function that return Object representation of XML document (using JAXB). I need to pass \"class\" object to JAXBContext constructor, but how I can get it

相关标签:
6条回答
  • 2021-02-19 16:56

    Take a look at this SO answer.

    Basically, the type T isn't available at runtime - Java generics are subject to erasure by the compiler.

    Fortunately you already have an instance of your class, so you can get the type information from there:

    public <T> readXmlToObject(String xmlFileName, T jaxbClass) {
    
       // if jaxbClass is an instance of the data object, you can do this: 
       JAXBContext context = JAXBContext.newInstance(jaxbClass.getClass());
    
       // alternatively if jaxbClass is an instance of the Class object: 
       JAXBContext context = JAXBContext.newInstance(jaxbClass);
       // ......
    }
    
    0 讨论(0)
  • 2021-02-19 16:59

    try to pass the class itself, something like this

    public <T> readXmlToObject(String xmlFileName, Class<T> class) {
    
    0 讨论(0)
  • 2021-02-19 16:59
    public class XYZ<T> {
        ...
        private Class<T> tClass;    
        ...
        public <T> readXmlToObject(String xmlFileName) {
           JAXBContext context = JAXBContext.newInstance(tClass);
           ...
        }
        ...
    } 
    
    0 讨论(0)
  • 2021-02-19 17:10

    Pass the class object instead and it's easy.

    public <T> T readXmlToObject(String xmlFileName, Class<T>  jaxbClass) {
           JAXBContext context = JAXBContext.newInstance( jaxbClass ); // T.class - here error, how to get it?
           Object o = context.createUnmarshaller().unmarshal( new File( xmlFileName ) );
           return jaxbClass.cast( o );
    }
    

    The idea here is that since you can't extract the type parameter from the object, you have to do it the other way around: start with the class and then manipulate the object to match the type parameter.

    0 讨论(0)
  • 2021-02-19 17:13

    You cannot get the class of at run time. Java implements Generics using Type Safe Erasure which means that the understanding of the Generic type is only applied at up through compilation. You must interogate the actual object at run time if you want to get its class.

    0 讨论(0)
  • 2021-02-19 17:16

    Don't listen to the others... you CAN get it.

    Simply change the type of the jaxbClass parameter to Class<T>:

    public <T> T readXmlToObject(String xmlFileName, Class<T> jaxbClass) {
       JAXBContext context = JAXBContext.newInstance(jaxbClass);
       .......
    }
    
    0 讨论(0)
提交回复
热议问题