Question

Is it possible to use JAXB to create an XML attribute from a function that includes a parameter? I'd like to do something like this:

@XmlRootElement
public class App {

    @XmlAttribute
    public boolean isOwned( User user ) {
        return user.ownsApp( getId( ) );
    }

}

How can I get the User parameter into this function call when marshalling the App class to XML? I'm not concerned with unmarshalling.

Was it helpful?

Solution

JAXB (JSR-222) limits the use of annotations to a field (i.e. foo) or property (i.e. bar). You can not use it on an arbitrary method as per the one in your question.

@XmlRootElement
public class App {

    @XmlAttribute  // VALID
    private boolean foo;

    private boolean bar;

    @XmlAttribute // VALID
    public boolean isBar() {
        return bar;
    }

    @XmlAttribute  // INVALID
    public boolean isOwned( User user ) {
        return user.ownsApp( getId( ) );
    }

}

OTHER TIPS

What is said by Blaise Doughan is valid, but I think you can work around it using a dirty way

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class App {
    @XmlTransient
    User u;

    @XmlAttribute  // VALID
    private boolean foo;

    private boolean bar;
    public App(SomeType x, User u, ...){
        this.u = u;
    }


    @XmlAttribute 
    public boolean isBar() {
        return bar;
    }

    @XmlAttribute  
    public boolean isOwned() {
        return u.ownsApp( getId( ) );
    }

}

You specify with @XmlAccessorType that you want it to return some specific values, and you omit to print the entire user with @XmlTransient, but indeed the isOwned() should work...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top