Skip to content

Instantly share code, notes, and snippets.

@SQiShER
Last active September 14, 2015 10:51
Show Gist options
  • Save SQiShER/dc5d456a9d39dd1c8e60 to your computer and use it in GitHub Desktop.
Save SQiShER/dc5d456a9d39dd1c8e60 to your computer and use it in GitHub Desktop.
Custom Differ for java-object-diff to add "equals-only" byte array support

To enable it, simply add it to the ObjectDifferBuilder like so:

ObjectDiffer objectDiffer = ObjectDifferBuilder.startBuilding()
  .differs().register(new ByteArrayDiffer.Factory())
  .build()

This will get rid of the Couldn't find a differ for type: [B message and instead provide simple support for byte arrays by just using Arrays.equals instead of doing a deep comparison.

import de.danielbechler.diff.NodeQueryService;
import de.danielbechler.diff.access.Instances;
import de.danielbechler.diff.differ.Differ;
import de.danielbechler.diff.differ.DifferDispatcher;
import de.danielbechler.diff.differ.DifferFactory;
import de.danielbechler.diff.node.DiffNode;
import java.util.Arrays;
public class ByteArrayDiffer implements Differ
{
public boolean accepts(final Class<?> type)
{
return type == byte[].class;
}
public DiffNode compare(final DiffNode parentNode, final Instances instances)
{
final DiffNode node = new DiffNode(parentNode, instances.getSourceAccessor());
if (instances.hasBeenAdded())
{
node.setState(DiffNode.State.ADDED);
}
else if (instances.hasBeenRemoved())
{
node.setState(DiffNode.State.REMOVED);
}
else
{
final byte[] baseValue = instances.getBase(byte[].class);
final byte[] workingValue = instances.getWorking(byte[].class);
if (!Arrays.equals(baseValue, workingValue))
{
node.setState(DiffNode.State.CHANGED);
}
}
return node;
}
public static class Factory implements DifferFactory
{
public Differ createDiffer(final DifferDispatcher differDispatcher,
final NodeQueryService nodeQueryService)
{
return new ByteArrayDiffer();
}
}
}
@ksoumi
Copy link

ksoumi commented Sep 14, 2015

In which class exactly should I add this?

ObjectDiffer objectDiffer = ObjectDifferBuilder.startBuilding()
.differs().register(new ByteArrayDiffer.Factory())
.build()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment