在Java 8中使用Java 7 Comparators [英] Using Java 7 Comparators in Java 8

查看:111
本文介绍了在Java 8中使用Java 7 Comparators的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况

我有一个OSGi项目,我正在尝试迁移到Java 8.在我的项目中,我有依赖项我OSGi-fied的第三方库(通过添加 MANIFEST.MF 文件并将元数据放入其中)。这些库是从只读SVN存储库中检出的,因此我可以在需要时检查更新,因此我不想进行任何其他更改,而不是 MANIFEST.MF 文件,因为我无法提交它们。

I have an OSGi project that I'm trying to migrate to Java 8. In my project, I have dependencies to third party libraries that I "OSGi-fied" (by just adding the MANIFEST.MF file and putting metadata into it). These libraries are checked out from read-only SVN repositories, so I just can checkout updates from then when needed and therefore I don't want to make any other changes than in the MANIFEST.MF file, since I cannot commit them.

问题

但是,这些库使用了许多匿名比较器,如:

However, these libraries use lots of anonymous Comparators like:

private static final Comparator heightComparator = new Comparator() {
    public int compare (Object o1, Object o2) {
        return ((Glyph)o1).getHeight() - ((Glyph)o2).getHeight();
    }
};

现在,显然 java.util.Comparator interface有一大堆需要实现的新方法(当然,这会导致编译错误)。但我真的想避免实现它们或切换到Lambda表达式,因为每次检查更新版本时修改原始源很可能会导致冲突。

Now, apparently the java.util.Comparator interface has a whole bunch of new methods that need to be implemented (which, of course, leads to compilation errors). But i really want to avoid implementing them or switch to Lambda expressions because modifying the original source would most likely result in conflicts each time I check out newer revisions.

Java用于努力实现向后兼容性,我想知道为什么这么简单且广泛使用的API部分需要(相对)大量迁移。我错过了什么或是否真的不可避免?

Java used to work hard on backwards compatibility and I wonder why such a simple and widely used part of the API needs so (relatively) much effort to migrate. Am I missing something or is it really unavoidable?

推荐答案

Java 8版本中的新方法比较器默认方法(Java 8中的一项新功能),它不仅包括方法签名,还包括默认实现。因此,较旧的 Comparator 实现应该可以在Java 8上正常工作,如果它们之前有效。

The new methods in the Java 8 version of Comparator are default methods (a new feature in Java 8) which not only include the method signature, but also a default implementation. Thus, older Comparator implementations should work just fine on Java 8 if they worked before.

如果某些东西不起作用,请告诉我们您的尝试以及错误消息。

If something is not working, please let us know what you are trying and what the error message is.

这篇关于在Java 8中使用Java 7 Comparators的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆