如果我有一个层次结构,如何处理JAXB.newInstance?

时间:2017-12-04 15:56:02

标签: java xml jaxb polymorphism

我有以下两个课程:

public class Solver implements FunctionI {
List<Double> pointsOfIntersectionX = new ArrayList<>();
List<Double> pointsOfIntersectionY = new ArrayList<>();
..realization

public class PolinomialFunction implements FunctionI{
private List<Double> arrayX;
private List<Double> arrayY;
..realization

这些类的实现彼此不同,所以我不能将它们作为一个。

然后我有以下

public interface XMLinput {
 static void writeToXMLForFunction(PolinomialFunction pol, String fileName) throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(PolinomialFunction.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(pol, new File(fileName));
     System.out.println("XML");
}
static void writeToXMLForResult(Solver solver, String fileName) throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(Solver.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(solver, new File(fileName));
    System.out.println("XML");
}

这就是我处理问题的方式,但我想知道,我只能创建一个将我的类(Solver / PolinomialFunction)写入XML文件的函数吗? 我所有的尝试都喜欢做以下事情:

JAXBContext jaxbContext = JAXBContext.newInstance(FunctionI.class);

或将FunctionI更改为抽象类而不是接口,并执行相同操作会导致此行出错。我该怎么处理呢? 的解决
解: 在方法调用的事实位置,你必须传递Class对象作为参数:

static void  writeToXML(FunctionI pol, String fileName, Class Tclass) throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(Tclass);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(pol, new File(fileName));
     System.out.println("XML");
}

方法调用的实际位置

XMLinput.writeToXML(polinomialFunctionG, file.getCanonicalPath(), polinomialFunctionG.getClass());

1 个答案:

答案 0 :(得分:3)

简短回答:是的,你可以有一个功能。

JAXBContext jaxbContext = JAXBContext.newInstance(PolinomialFunction.class,FunctionI.class);

但是,看起来你错过了一些关于JAXB的东西...... 一开始:-):

  1. JAXBContext及其编组程序可以处理它们中的任何类和层次结构,只要它们在JAXBContext中已知(以不同的方式传递到JAXBContext.newInstance(上面的一个示例,但您可以将包名称作为如果包中有许多JAXB类,则为字符串)

  2. 为每次调用创建JAXBContext的新实例都是昂贵的操作 - 在方法之外执行一次并将其重用于marshallers。 Marshaller不是线程安全的,但创建一个并不昂贵,所以继续在方法中创建一个新的marshaller。

  3. P.S。直接继承没有任何意义。 JAXB通过类中的注释进行管理(我在您的示例中没有看到任何内容 - 您有吗?)