使用Diff-Match Patch在Java中逐行区分两个字符串



我一直在寻找一种简单的方法,用Java对两个字符串逐行进行Myers Diff。

据此,谷歌差异匹配补丁库具有此功能。但是,在Java版本中,引用的方法是受保护的和/或包保护的!

我找不到另一个(1(这样做的库,而且(2(似乎维护得很好。

因此,我最终使用反射来获得谷歌的一个让我这样做。我想避免任何人不得不重新实施它,所以我会把我所做的作为答案发布出来。

这是我想出的代码。请随意编辑/修复。

我不确定是否有任何反思的最佳实践(除了"不要"(,但如果有人有想法,我肯定想学习。

List<Diff> diff = new diff_match_patch() {
// anonymous extension
List<Diff> getLineDiff(String a, String b) throws NoSuchFieldException, IllegalAccessException {
LinesToCharsResult res = this.diff_linesToChars(a, b);
// extract protected fields
Class<?> clazz = res.getClass();
Field chars1 = clazz.getDeclaredField("chars1");
Field chars2 = clazz.getDeclaredField("chars2");
Field lineArray = clazz.getDeclaredField("lineArray");
chars1.setAccessible(true);
chars2.setAccessible(true);
lineArray.setAccessible(true);
// follow the docs https://github.com/google/diff-match-patch/wiki/Line-or-Word-Diffs
String chars1Inst = (String) chars1.get(res);
String chars2Inst = (String) chars2.get(res);
List<String> lineArrayInst = (List<String>) lineArray.get(res);
LinkedList<Diff> diff = this.diff_main(chars1Inst, chars2Inst, false);
// convert back to original strings
this.diff_charsToLines(diff, lineArrayInst);
return diff;
}
}.getLineDiff(expected, output);