如何在Java 8编译时确保方法签名“实现”功能界面 [英] How to ensure at Java 8 compile time that a method signature "implements" a functional interface

查看:115
本文介绍了如何在Java 8编译时确保方法签名“实现”功能界面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java 8中是否存在的任何模拟实现方法的关键字?

Is there in Java 8 any analogue for implements keyword for methods?

假设我有一个功能interface:

Let's say I have a functional interface:

@FunctionalInterface
interface LongHasher {
    int hash(long x);
}

包含3种静态方法的库实现这个功能界面:

And a library of 3 static methods "implementing" this functional interface:

class LongHashes {
    static int xorHash(long x) {
        return (int)(x ^ (x >>> 32));
    }
    static int continuingHash(long x) {
        return (int)(x + (x >>> 32));
    }
    static int randomHash(long x) {
         return xorHash(x * 0x5DEECE66DL + 0xBL);
    }
}

将来我希望能够互换使用任何对这3种方法的引用作为参数。例如:

In the future I want to be able to interchangeably use any of references to these 3 methods as a parameter. For example:

static LongHashMap createHashMap(LongHasher hasher) { ... }
...
public static void main(String[] args) {
    LongHashMap map = createHashMap(LongHashes::randomHash);
    ...
}

如何在编译时确保 LongHashes :: xorHash LongHashes :: continueHash LongHashes :: randomHash 具有相同的签名LongHasher.hash(长x)

How can I ensure at compile time that LongHashes::xorHash, LongHashes::continuingHash and LongHashes::randomHash have the same signature as LongHasher.hash(long x)?

推荐答案

你没有要求的语法结构。但是,您可以在显式将方法引用分配给接口时创建静态常量:

There's no such syntax construction you're asking for. However you can create a static constant where you explicitly assign the method reference to your interface:

class LongHashes {
    private static final LongHasher XOR_HASH = LongHashes::xorHash;
    private static final LongHasher CONTINUING_HASH = LongHashes::continuingHash;
    private static final LongHasher RANDOM_HASH = LongHashes::randomHash;

    static int xorHash(long x) {
        return (int)(x ^ (x >>> 32));
    }
    static int continuingHash(long x) {
        return (int)(x + (x >>> 32));
    }
    static int randomHash(long x) {
         return xorHash(x * 0x5DEECE66DL + 0xBL);
    }
}

这样,无论是方法签名还是方法签名,您的编译都会中断界面以不兼容的方式变化。如果你想要你可以声明它们 public 并使用而不是方法引用。

This way your compilation will break if either method signature or interface changes in incompatible way. If you want you may declare them public and use instead of method references.

如果你关心这些静态lambda将在运行时挂在内存中,您可以将此声明移动到单独的类(例如,嵌套),它编译但从未加载。

If you care that these static lambdas will be hanging in memory at runtime, you can move this declaration to the separate class (for example, nested), which compiles but never loaded.

这篇关于如何在Java 8编译时确保方法签名“实现”功能界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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