Skip to content

Commit

Permalink
Fix AtomicReference marshalling. Closes #326.
Browse files Browse the repository at this point in the history
  • Loading branch information
ablekhman authored and joehni committed Sep 22, 2023
1 parent 289ae78 commit 6444f7a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,23 +43,29 @@ public boolean canConvert(final Class<?> type) {
@Override
public void marshal(final Object source, final HierarchicalStreamWriter writer, final MarshallingContext context) {
final AtomicReference<?> ref = (AtomicReference<?>)source;
writer.startNode(mapper.serializedMember(AtomicReference.class, "value"));

final Object object = ref.get();
final String name = mapper.serializedClass(object != null ? object.getClass() : null);
writer.addAttribute(mapper.aliasForSystemAttribute("class"), name);
context.convertAnother(ref.get());
writer.endNode();
if (object != null) {
writer.startNode(mapper.serializedMember(AtomicReference.class, "value"));

final String name = mapper.serializedClass(object.getClass());
writer.addAttribute(mapper.aliasForSystemAttribute("class"), name);
context.convertAnother(object);
writer.endNode();
}
}

@Override
public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
reader.moveDown();
if (reader.hasMoreChildren()) {
reader.moveDown();

final Class<?> type = HierarchicalStreams.readClassType(reader, mapper);
final Object value = context.convertAnother(context, type);
reader.moveUp();
return new AtomicReference<>(value);
final Class<?> type = HierarchicalStreams.readClassType(reader, mapper);
final Object value = context.convertAnother(context, type);
reader.moveUp();
return new AtomicReference<>(value);
} else {
return new AtomicReference<>();
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -108,12 +108,17 @@ public void testAtomicReference() {

@SuppressWarnings("unchecked")
public void testAtomicReferenceWithOldFormat() {
assertEquals(new AtomicReference<String>("test").get(), ((AtomicReference<String>)xstream.fromXML("" //
assertEquals(new AtomicReference<>("test").get(), ((AtomicReference<String>)xstream.fromXML("" //
+ "<java.util.concurrent.atomic.AtomicReference>\n" //
+ " <value class='string'>test</value>\n" //
+ "</java.util.concurrent.atomic.AtomicReference>")).get());
}

public void testEmptyAtomicReference() {
final AtomicReference<?> atomicRef = new AtomicReference<>();
assertBothWays(atomicRef, "<atomic-reference/>");
}

public void testAtomicReferenceWithAlias() {
xstream.aliasField("junit", AtomicReference.class, "value");
final AtomicReference<String> atomicRef = new AtomicReference<>("test");
Expand Down

0 comments on commit 6444f7a

Please sign in to comment.