1
我想填充数组中的方法。但我必须以一种奇怪的方式做到这一点:将方法添加到对象数组
public class AssignFunctionalInterfaceTest {
public void test() {
TestEntity t = new TestEntity();
// compiles
Supplier<Integer> a = t::getB;
Object[] b = new Object[] {"42", a};
// compiles
Object[] b2 = new Object[] {"42", (Supplier<Integer>) t::getB};
// doesn't compile. Error message:
// "The target type of this expression must be a functional interface"
Object[] b3 = new Object[] {"42", t::getB};
}
public static class TestEntity {
public Integer getB() {
return 0;
}
}
}
我真的很想找到一种方法来使第三项任务的工作。有任何想法吗?
为什么“42”是数组中的值?它需要成为?否则你可以创建一个'供应商 []'而不是'Object []' –
CraigR8806
这实际上是关于混合在一起的事情。我明白你的观点,但对我的问题没有帮助。 –
我可能对此有错,但我想为什么它不会让你只是将方法引用放在数组中,是因为它需要以某种方式与'Supplier <>'相关联,因为它改变了它的方式由编译器查看。我认为'Supplier <>'类在指针和编译器的实际方法之间建立了联系。 – CraigR8806