简体   繁体   English

如何将多态应用于xml反序列化?

[英]How to apply polymorphism to xml deserialization?

I have two types of xml:我有两种类型的 xml:

<exec><cmd>STATISTIC</cmd><param></param></exec>

<exec><cmd>FILE_TO_CLIENT</cmd><param><filePath>"/opt/tst"</filePath><msg>"ls- la"</msg></param></exec>

I need to pass them to function that might return two types of class object我需要将它们传递给可能返回两种类型的类对象的函数

class Statistic    {
}

class FileToClient
{
  String msg;
  String filePath;
}

In case the message is of type statistic - no fields are required.如果消息是statistic类型 - 不需要字段。 In case it is file_to_client , msg and filePath fields should be filled from xml.如果是file_to_client ,则应从 xml 填充msgfilePath字段。

How should I organize my class hierarchy so that the deserializer function could return both type of objects?我应该如何组织我的类层次结构,以便反序列化器函数可以返回这两种类型的对象?

First of all.... Classes in java ALWAYS starts with UPPERCASE .首先...... java中的类总是UPPERCASE开头。
Second your question is not clear, but I will try to explain basic inheritance.其次,您的问题不清楚,但我将尝试解释基本继承。


If you want both classes being same type to be returned by same method you need to have a common Parent class.如果您希望通过相同的方法返回相同类型的两个类,您需要有一个公共的Parent类。 All classes in Java inherits from Object class, but better if you define your own parent like this: Java 中的所有类都继承自 Object 类,但如果您像这样定义自己的父类会更好:

// parent class common to others
class YourParent {
    // put here any common attributes for child classes
}

Then make your child classes extend from parent:然后让你的子类从父类扩展:

class Statistic extends YourParent 
{
}

class FileToClient extends YourParent 
{
String msg;
String filePath;

}

Finally, you can use both FileToClient and Statistics as YourParent classes.最后,您可以使用FileToClientStatistics作为YourParent类。

For example, as return type in a method:例如,作为方法中的返回类型:

public YourParent doSomething() {
    if (something)
        FileToClient f = //
        return f;  // valid
    } else {
        Statistic s = //
        return s;  // valid also!!!
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM