【问题标题】:Is it possible to modify method through reflections before webservice is created?是否可以在创建 web 服务之前通过反射修改方法?
【发布时间】:2013-05-06 03:46:48
【问题描述】:

我有一个 web 服务,它在动作参数中使用不可变类(这是因为其他开发人员在该项目上工作)——这意味着没有公共设置器。没有公共设置器意味着 web 服务不会看到属性。

这个想法是创建私有 setter 并添加一个带有 PostConstruct 注释的 init 方法到我的 web 服务类。在 init 方法中,所有私有 setter 都可以通过反射访问。

问题是使用PostConstruct 注释的init 方法在部署时根本没有被调用。我正在使用 JAX-WS 并将项目部署到 Glassfish。

【问题讨论】:

  • 您在写问题时应该更加小心。

标签: java web-services reflection jaxb jax-ws


【解决方案1】:

你想做的事情听起来像是一个可怕的黑客攻击。

如果我没记错的话,您的问题是,在您的操作中用作参数的对象是不可变的。幸运的是,有很多方法可以使用注释自定义 JAXB 映射。应该可以保持您的类不可变,同时使这些字段对 JAXB 可见。

来自this answer,我明白了:

package blog.immutable;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="customer")
@XmlAccessorType(XmlAccessType.NONE)
public final class Customer {

    @XmlAttribute
    private final String name;

    @XmlElement
    private final Address address;

    @SuppressWarnings("unused")
    private Customer() {
        this(null, null);
    }

    public Customer(String name, Address address) {
        this.name = name;
        this.address = address;
    }

    public String getName() {
        return name;
    }

    public Address getAddress() {
        return address;
    }

}

如果你不喜欢上面的代码需要一个无参数构造函数Customer(),你可以多看看这个complicated approach

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    相关资源
    最近更新 更多