本文介绍了如何更改函数引用的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 Java 8允许我使用方法声明来实现任何接口,只要它只包含一个方法即可。 然而,一旦定义了类型, 我的代码: 固有类型。当它出现在使用或分配给函数接口类型的上下文中时,编译器将创建一个的对象,该对象使用 MyConsumer ,但是这个对象将永远只是一个 IntConsumer ,仅此而已。 Java8 lets me use a method declaration as implementation of any of my interfaces, as long as it only contains one method.However once it is defined, the type cannot be changed.My code:import java.util.function.IntConsumer;public class A { interface MyConsumer { void doSomething(int i); } public static void main(String[] args) { IntConsumer i = A::consume; MyConsumer i2 = A::consume; IntConsumer i3 = (IntConsumer) i2; // ClassCastException MyConsumer i4 = (MyConsumer) i; // ClassCastException IntConsumer i5 = i2; // does not compile MyConsumer i6 = i; // does not compile IntConsumer i7 = i2::doSomething; // workaround, as suggested by @Eran http://stackoverflow.com/a/35846001/476791 MyConsumer i8 = i::accept; Object i9 = A::consume; // does not compile Object i10 = (IntConsumer) A::consume; // works Object i11 = (MyConsumer) A::consume; // works Object i12 = (MyConsumer) (IntConsumer) A::consume; // does not work } static void consume(int i) { System.out.println(i); }}Note: if you inline some of the variables, then some of the non-working examples suddenly start to work.My thoughts in detail:if IntConsumer i = A::consume is valid, then A::consume has to implement IntConsumerif MyConsumer i2 = A::consume is valid, then A::consume has to implement MyConsumerif A::consume implements both, IntConsumer and MyConsumer, then casting should be possibleIs there another way to "cast" or "change" the type of the consumer afterwards? 解决方案 A::consume has no inherent type. When it appears in a context in which it is being used or assigned to a functional interface type, the compiler will create an object of that type implemented using A::consume. Once you have that, you have an object of that specific functional interface type. It's not a method; it's a perfectly normal object. Java objects can't pretend to be other types their real type doesn't implement or extend.So once you have an IntConsumer, you can't cast it to a MyConsumer. You can use it to get a method reference that can then become a new MyConsumer, but that one object will always be just an IntConsumer, nothing more. 这篇关于如何更改函数引用的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-16 07:18