如何在Java中将“ <ClassName> .class”作为参数传递?

时间:2019-09-20 07:29:10

标签: java jaxb

我正在尝试制作一种将POJO对象转换为XML字符串的通用方法。

我正在尝试使用这种方法来实现这一目标。

public class Util{

    public static String jaxbObjectToXML(Object xmlObj) {
        String xmlString = "";
        try {
            JAXBContext context = JAXBContext.newInstance(POJO.class);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.marshal(xmlObj, stringWriter);
            xmlString = stringWriter.toString();
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return xmlString;
    }
}

现在在JAXBContext context = JAXBContext.newInstance(**POJO.class**);行中,我试图将这个POJO值设为通用。 就像我可以传递类名,对象或可以完成工作的东西一样。还要在方法中添加适当的参数。

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

@XmlRootElement
public class Util {
    @XmlElement
    private String name;
    @XmlElement
    private String description;

    public static void main(String[] args) {
        Util xmlObj = new Util();
        xmlObj.name = "Alex";
        xmlObj.description = "Alex Rose";
        jaxbObjectToXML(xmlObj, xmlObj.getClass());
    }

    public static <T> String jaxbObjectToXML(T xmlObj, Class<? extends T> aClass) { {
        String xmlString = "";
        try {
            JAXBContext context = JAXBContext.newInstance(aClass);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.marshal(xmlObj, System.out);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return xmlString;
    }
}

输出:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<util>
    <name>Alex</name>
    <description>Alex Rose</description>
</util>

JAXBContext.newInstance(xmlObj.getClass());