Diff Two Strings Line-By-Line in Java using Diff-Match-Patch

风格不统一 提交于 2020-02-29 07:13:25

问题


I was looking for an easy way to do a Myers Diff on two Strings line-by-line in 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!

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.


回答1:


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);


来源:https://stackoverflow.com/questions/60386661/diff-two-strings-line-by-line-in-java-using-diff-match-patch

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!