Java Webservice and polymorphism

Let's say I have the following strucutre

public class Mammal
{
    @WebMethod
    public ArrayList<Mammal> getAll(){ return null; }
    @WebMethod
    public String speak(){ return "Unable to speak"; }
    @WebMethod
    public Mammal me(){ return this; }  
}

@WebService
public class Human extends Mammal
{
    @WebMethod
    public ArrayList<Human> getAll(){ /* code to return all humans as ArrayList<Human> */ }
    @WebMethod
    public String speak() { return "Hai!"; }
    @WebMethod(operationName="GetHuman")
    public Human me(){ return this; }
}

      

Now if you can see that Mammal me () and Human me () are overridden and that works great and the WSDL is generated as it should be because I add the Name = "" operation.

So far so good, now the method returning ArrayList doesn't work. Somehow it says that ArrayList cannot override ArrayList, which in my opinion should be possible?

Now I have found a workaround for this and the result looks like this

In the Mammal class, I have this: public ArrayList getAll(){ return null; }

And I leave the Humna class intact, it works now.

Nevertheless! This makes it impossible to extend Human and cancel a method from a new subclass, so I'm back to square again.

How to solve this?

Let's say I want to access a Webservice from a C # application, after which I want the method to have a List Human or List Anywhere-extended-Mammal return type, without having to enter text on the other side!

+2


source to share


2 answers


The sample code shouldn't compile even without the web service related annotations. List<Human>

NOT a subtype List<Mammal>

. However if you are using List<? extends Mammal>

in your base class then everything should work fine.

public class Mammal
{
    @WebMethod
    public List<? extends Mammal> getAll() { return null; }
}

public class Human extends Mammal {
    @WebMethod
    public List<Human> getAll() { return null; }
}

      



If you want to expand Human

even further you will need to use

public class Human extends Mammal {
    @WebMethod
    public List<? extends Human> getAll() { return null; }
}

      

+4


source


What if you are trying to use a real array instead of a collection? I don't think web services frameworks work well with generics.

EDIT : Something like this:



public class Mammal
{

    @WebMethod
    public Mammal[] getAll() { return null; }

    ...

}

@WebService
public class Human extends Mammal
{

    @WebMethod
    public Human[] getAll() { return null; }

    ...

}

      

0


source







All Articles