我有两种产生“消费者”的工厂方法,它们使用不同的方法=> lambda和方法参考:
@SuppressWarnings("Convert2MethodRef")
public Consumer<String> asLambdaPrintStringConsumer(){
return x -> System.out.println(x);
}
public Consumer<String> asMethodRefPrintStringConsumer(){
return System.out::println;
}
我发现在第一种情况下[asLambdaPrintStringConsumer()
,方法返回对同一对象的引用
@Test
public void shouldSameFromFactoryMethod_AsLambda() {
Consumer<String> consumerA = asLambdaPrintStringConsumer();
Consumer<String> consumerB = asLambdaPrintStringConsumer();
Assert.assertSame(consumerA, consumerB);//consumerA == consumerB --> true
}
但是在第二个(asMethodRefPrintStringConsumer()
)中,对象是不同的
@Test
public void shouldNotSameFromFactoryMethod_AsMethodRef() {
Consumer<String> consumerA = asMethodRefPrintStringConsumer();
Consumer<String> consumerB = asMethodRefPrintStringConsumer();
Assert.assertNotSame(consumerA, consumerB);//consumerA == consumerB --> false
}
直接方法返回与shouldNotSameFromFactoryMethod_AsMethodRef()
相同的结果:
@SuppressWarnings("Convert2MethodRef")
@Test
public void shouldNotSameFromLambda() {
Consumer<String> consumerA = s -> System.out.println(s);
Consumer<String> consumerB = s -> System.out.println(s);
Assert.assertNotSame(consumerA, consumerB);//consumerA == consumerB --> false
}
,接下来我用参考其他静态方法的方法测试了工厂方法
public static Consumer<String> asMethodRefFromStaticMethodStringConsumer() {
return FunctionalInterfaceTest::print;
}
public static void print(String string){
System.out.println(string);
}
并获得与第一次测试(asLambdaPrintStringConsumer
)相同的结果:
@Test
public void shouldSameFromFactoryMethod_AsMethodRef() {
Consumer<String> consumerA = asMethodRefFromStaticMethodStringConsumer();
Consumer<String> consumerB = asMethodRefFromStaticMethodStringConsumer();
Assert.assertSame(consumerA, consumerB );//consumerA == consumerB --> true
}
请描述我,什么是技巧 ...
在测试中,我使用了jdk-11.0.1
和jdk-13.0.1
。
以下表达式是否等效?