Java 8或Java 11-我通过枚举构造函数加载静态函数接口.然后,我try 与相同的成员引用进行比较.要么代码无法编译,要么与相同函数接口的比较失败.使用.equals和==进行比较以及使用.hashcode()进行比较都会失败.我已经创建了下面的POJO测试,它演示了这个问题并指出了相关的特定点.我想编写代码"如果实例成员等于specific-static-functional-interface-method-x,,则执行..."
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import java.util.function.Function;
import org.junit.jupiter.api.Test;
enum MethodReferenceEnum {
One("One", MethodReferenceInterface::one),
Two("Two", MethodReferenceInterface::two);
public String name;
public Function<String, Integer> method;
private MethodReferenceEnum(String aName, Function<String, Integer> aMethod) {
name = aName;
method = aMethod;
}
}
interface MethodReferenceInterface {
public static Integer one(String aString) {
return 1;
}
public static Integer two(String aString) {
return 2;
}
}
class MethodRererencesTest {
@Test
void LocalUseTest() {
// This performs in JavaSE-8 (jdk-1.8.0_271) and JavaSE-11 (jdk-11.0.11).
// These succeed in placing the member references in variables.
Function<String, Integer> choice1a = MethodReferenceInterface::one;
Function<String, Integer> choice1b = MethodReferenceEnum.One.method;
Function<String, Integer> choice2a = MethodReferenceInterface::two;
// These succeed in executing the member references from variables.
assertEquals(1, choice1a.apply("A").intValue());
assertEquals(1, choice1b.apply("B").intValue());
assertEquals(2, choice2a.apply("2nd").intValue());
// Why does the following fail to compile?
//
// assertEquals(choice1a, MethodReferenceInterface::one);
//
// ^ assertEquals fails to compile due to:
// The method assertEquals(Object, Object) in the type Assert is not applicable
// for the arguments (Function<String, Integer), MethodReferenceInterface::one)
// ^ MethodReferenceInterface::one fails to compile due to:
// The target type of the expression must be a functional interface
// Compiles and succeeds; expected.
assertEquals(choice1a, choice1a);
// This compiles, and succeeds,
// but why do they not compare equal?
assertNotEquals(choice1a, choice1b);
}
}
最后一行和问题总结了这个问题.我在上面运行了测试,它通过了.问题在于,包含相同成员引用的变量在比较时并不相等.这发生在Java 8和Java 11中.