使用 Diff-Match-Patch 在 Java 中逐行区分两个字符串 [英] Diff Two Strings Line-By-Line in Java using Diff-Match-Patch
问题描述
我一直在寻找一种简单的方法来在 Java 中对两个字符串逐行进行 Myers Diff.
I was looking for an easy way to do a Myers Diff on two Strings line-by-line in Java.
根据this,Google diff-match-patch 库 具有此功能.但是,在 Java 版本中,引用的那些方法是受保护的和/或受包保护的!
According to this, the Google diff-match-patch library has this feature. But, in the Java version, those methods referenced are protected and/or package-protected!
我找不到其他库 (1) 执行此操作,并且 (2) 似乎维护良好.
I couldn't find another library that (1) does this, and (2) appears to be well-maintained.
所以我最终使用反射让谷歌让我这样做.我想避免任何人不得不重新实现它,所以我会发布我所做的作为答案.
So I ended up using reflection to get the Google one to let me do this. I want to avoid anyone having to re-implement it, so I will post what I did as an answer.
推荐答案
这是我想出的代码.随意编辑/修复.
Here is the code I came up with. Feel free to edit/fix.
我不确定任何反思的最佳实践(除了不要"),但如果有人有想法,我肯定想了解.
I'm not sure about any best-practices for reflection (besides "don't"), but I would definitely like to learn if anyone has thoughts.
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);
这篇关于使用 Diff-Match-Patch 在 Java 中逐行区分两个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!