Get “Class” object from generic type T

后端 未结 6 1802

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条回答
  •  Happy的楠姐
    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  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);
       // ......
    }
    

提交回复
热议问题