有没有办法在Java 8中引用一组方法,这些方法的签名是以重载方式变化的?
更准确地说,我希望这段代码能够正常工作:
public class OverloadingMethodRef
{
public static void foo ( int x ) {
System.out.println ( "An integer: " + x );
}
public static void foo ( String x ) {
System.out.println ( "A String: " + x );
}
/**
* I want it to work without this
*/
// public static void foo ( Object x ) {
// if ( x instanceof Integer ) foo ( (int) x ); else foo ( ( String ) x );
// }
public static void main ( String[] args )
{
// Compile error, it wants a precise reference to one of them
Consumer<Object> c = PolymorphicMethodRef::foo;
foo ( "bla" ); // despite it could get it
foo ( 1 ); // and here too
}
}
我不能添加 public static void foo ( Object x )
,因为有很多方法需要传递给另一个方法,我不想写包装器。到目前为止,我只能通过反射来实现(可以接收param.getClass()
),但我必须调用的方法具有不同的参数(>=1),每次都需要将它们放入数组中,再将其类型放入另一个数组中。
void foo(Object x)
,然后从中获取一个消费者,但它仍然总是调用该确切的方法(带有 Object 参数),永远不会解析为其他任何东西。 - M. Prokhorov