使用自定义类作为JAX-WS返回类型?

问题描述:

我正在使用NetBeans的Web服务生成工具.我看过可用的教程,但是找不到有关如何将自定义类用作返回类型的任何信息.我读过的大多数教程都没有《 Hello World》那么复杂:它们采用并返回诸如Strings之类的简单类型.

I'm using NetBeans's Web Service generation tools. I've looked at the tutorials available, but cannot find anything on how to use a custom class as a return type. Most of the tutorials I've read are no more complex than Hello World: they take and return simple types like Strings.

所以说我想要一个具有3个字段的类:一个字符串,一个整数和一个double [].到目前为止,传递我自己的类的唯一方法是创建信封类",该类不包含任何方法,一个无参数的构造函数,并且所有字段都声明为public.我更喜欢编写标准的Java类.显然,我无法跨SOAP发送方法,但我本以为在编组类时仅忽略字段,可以忽略该方法.

So say I want a class that has 3 fields: a String, an int and a double[]. So far, the only way I can pass my own classes is by creating "envelope classes", with no methods, a parameter-less constructor, and with all fields declared public. I'd prefer to write standard Java classes. Obviously I cannot send the methods across SOAP, but I would have thought there was a way to ignore the methods when Marshalling the class, and only Marshall the fields.

有人告诉我,有一些注释可以简化此操作,但是我找不到有关如何实现它们的任何教程.任何指导将不胜感激.

Somebody has told me there are Annotations that facilitate this, but I can't find any tutorials on how to implement them. Any guidance would be greatly appreciated.

JAX-WS使用 JAXB 用于映射类型,因此类应符合该规范.您可以在 java.xml.bind.annotations 包.

JAX-WS uses JAXB for mapping types, so classes should conform to that specification. You can find JAXB annotations in the java.xml.bind.annotations package.

如果您要封送未注释的类,请遵循适用于JavaBeans的规则:

If you want to marshal a non-annotated class, conform to the rules for JavaBeans should work:

public class Foo {
  private String bar;
  public String getBar() { return bar; }
  public void setBar(String bar) { this.bar = bar; }

  public static void main(String[] args) {
    Foo foo = new Foo();
    foo.setBar("Hello, World!");
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    JAXB.marshal(foo, out);
    foo = (Foo)
        JAXB.unmarshal(new ByteArrayInputStream(out.toByteArray()), Foo.class);
    System.out.println(foo.getBar());
  }
}

如果要对参数使用构造函数,请参见 spec 有关工厂方法和适配器.

If you want to use constructors with arguments, etc. look at the parts of the spec about factory methods and adapters.