Search code examples
javaweb-servicescastingobject-object-mapping

webservice returning Object1.java not the same as Object1.java in the client app?


The same object is defined twice in different packages:

packageX/Object1.java

and

packageY/Object1.java

[Background: packageX is part of a webclient service, getting objects from a server. packageY is a java client using the objects retrieved by this webclient service].

A function from packageX returns Object1, and the compiler throws an error when I try to use this object as an Object1 from packageY (which I can understand).

=> Is mapping packageX/Object1.java to packageY/Object1.java my only option? Or do I miss something?


Solution

  • You appear to be missing something. Java makes things easier on the programmer by letting you use the "shorthand" of just a class's short name if you're in the same package or if you import the class, but each class's real name is its fully-qualified class name. In your case, you don't have Object1 defined twice, you have one class named packageX.Object1 and another unrelated class named packageY.Object1. If you try to use both in the same scope, you have to specify the entire class name for at least one of the variables:

    import packageX.Object1;
    ...
    private Object1 foo; // this is a packageX.Object1;
    private packageY.Object1 bar;
    

    There's no way to "map" from one to the other besides converting between them like you would between any two other classes that didn't have similar names.

    Most likely, you should be using the same implementation in both the server and client sides. You're talking about "Web services", but this is generally only an issue if you're using Java serialization, not JSON.