Java 如何将两个不同的对象映射到一起

Java 如何将两个不同的对象映射到一起,java,xml,web-services,proxy,Java,Xml,Web Services,Proxy,在我当前的项目中,我有两个模块ModuleA和ModuleB,在ModuleA和ModuleB中,我有一个名为“Student”的类(相同的类名,相同的属性,但出于某种目的,ModuleA必须调用ModuleB来完成实际任务)。它们通过Web服务相互通信。现在我希望ModuleA web服务调用ModuleB proxy来执行实际任务 在我的ModuleA web服务中,我有一个创建记录的方法: public void createStudent(ModuleA.Student student)

在我当前的项目中,我有两个模块ModuleA和ModuleB,在ModuleA和ModuleB中,我有一个名为“Student”的类(相同的类名,相同的属性,但出于某种目的,ModuleA必须调用ModuleB来完成实际任务)。它们通过Web服务相互通信。现在我希望ModuleA web服务调用ModuleB proxy来执行实际任务

在我的ModuleA web服务中,我有一个创建记录的方法:

public void createStudent(ModuleA.Student student){
    // Here will call ModuleB proxy to do the actual task which is create.

    *moduleBFacade().createStudent(   );*
}
在我的ModuleB代理中:

public void createStudent(ModuleB.Student student){}
所以现在的问题是,我无法将moduleA对象传递到createStudent方法中,因为它只将moduleB对象作为参数


你知道怎么处理这个问题吗?请给我一些建议。

循环依赖==糟糕的设计


重新设计模块以删除循环依赖项。

您不能更改Java中对象的类。此外,不能将两个类“合并”为一个类。您可以做的是引入一个公共接口,但为此您必须拥有这两个类的源代码

如果您不能更改这两个类,那么手动将
ModuleA.Student
转换为
ModuleB.Student
并返回是最佳选择

另外,你也可以使用反射。假设两个类都有相同的属性名,那么从一个类到另一个类的映射应该不会有问题


上面的示例假设所有字段都是私有的。如果不是,则可以使用方法(模块将setter名称映射为getter名称)。

当您使用WS调用时,可以将moduleA.Student转换为xml,然后更改xml的命名空间,然后从xml实例化moduleB.Student对象

比如:

String xmlA = moduleA.Student.toXml();
//Change namespace. Also, Compare the genrated xml of ModuleA and ModuleB.

ModuleB.BStudent studentB= StudentDocument.Factory.parse(xmlA, ..);//second argument can be diff namespace

*moduleBFacade().createStudent(studentB);

听起来可能不对,但在这里:
Java代码

假设传递的学生对象的类型为ModulesStudent

//create a new bStudent with main criteria 
ModuleBStudent bStudent = new ModuleBStudent();
bStudent.setStudentId(student.getStudentId());
bStudent.setStudentNo(student.getStudentNo());

//finally
moduleBFacade().createStudent(bStudent);
更新

由于您的对象在这两个包中是相同的,并且您正在创建一个web服务,因此我建议这样做,实际上它被称为Simple。Simple帮助您将对象序列化为XML并反序列化,非常简单。

您可以使用它复制到类似的bean(注意,这是一个浅拷贝)

通过注释添加了太多额外的约束。。。这是家庭作业吗?对不起,我什么都没有。为什么你不能重新设计?如果它不起作用,那么您当前的代码为您做了什么?您用于访问Web服务的框架是什么?。大多数WS-framework,如Axis2,将使用一些绑定框架来基于wsdl将对象打包为xml。绑定框架提供了toXml()的实现,以及wsdl编译期间StudentDocument等帮助类。我正在使用JAXB将java绑定到xmlhi Adrian谢谢,我尝试了你的方法反射对象没有错误,但它没有返回任何值,studentA值不会反射到studentB?我不明白,你能重新措辞你的问题吗?
convert
方法应该一次将所有属性从A复制到B,因此要将值从B返回到A,必须再次调用
convert
以相反的方式。
String xmlA = moduleA.Student.toXml();
//Change namespace. Also, Compare the genrated xml of ModuleA and ModuleB.

ModuleB.BStudent studentB= StudentDocument.Factory.parse(xmlA, ..);//second argument can be diff namespace

*moduleBFacade().createStudent(studentB);
//create a new bStudent with main criteria 
ModuleBStudent bStudent = new ModuleBStudent();
bStudent.setStudentId(student.getStudentId());
bStudent.setStudentNo(student.getStudentNo());

//finally
moduleBFacade().createStudent(bStudent);