I tried to use anonymous inner classes with initializers syntax to serialize JAXB generated objects, and noticed that it works on endpoints but not with RestTemplate. I am wondering why is it working in one case and not the other?
To give example, this is sample endpoint in Spring which returns JAXB generated Profile instance:
@PayloadRoot(namespace = NAMESPACE_URI, localPart = SERVICE_NAME)
@ResponsePayload
public Profile getProfile(@RequestPayload  GetProfile request) {
    // do stuff with service that returns Profile
    return service.doStuff(request);
}
Now, when i have service returning the anonymous instance of Profile, there are no serialization issues:
return new Profile() {
    {
        setBirthday(user.getBirthday());
        setEmailAddress(user.getEmailAddress());
        setFirstname(user.getFirstname());
        setGender(user.getGen());
        // and so on
    }
};  
However, when i try to use anonymous inner classes as argument to RestTemplate, then i get JAXB error regarding the not supported anonymous classes.
"a non-static inner class, and JAXB can't handle those. this problem is related to the following location..."
    private UpdateProfile createUpdateProfileRequest(final UpdateProfile request) {
    return new UpdateProfile() {
        {
            setProfileV2(getProfile(request));
        }
    };
}
private ProfileV2 getProfile(UpdateProfile request) {
    ProfileV2 profile = new ProfileV2();
    ProfileUpdate profileUpdate = request.getProfileUpdate();
    profile.setBirthday(profileUpdate.getBirthday());
    profile.setFirstname(profileUpdate.getFirstname());
    return profile;
}
I have read this post: What is Double Brace initialization in Java?
And i generally don't have use case where these objects could turn into container managed singletons - memory leaks.
There is a mention of serialization issues, but no details and i would like to understand this.
Since i am using JAXB for serialization on endpoints too, why it is possible for JAXB to serialize such objects as outgoing data on endpoints but not within RestTemplate.postForObject(...).
 
    