zak*_*mck 4 lambda java-8 method-reference
有没有办法在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
}
}
Run Code Online (Sandbox Code Playgroud)
我负担不起public static void foo ( Object x ),因为我有很多方法可以传递给另一个方法而且我不想写包装器.到目前为止,我只能通过反射(可以接收param.getClass())来做到这一点,但我必须调用的方法有不同的参数(> = 1),每次我需要将它们放在一个数组中,加上它们在另一个数组中的类型.
方法引用支持使用与普通方法调用相同的规则进行重载.当你有一个Consumer<Object>,你可以将任意Object实例传递给它的accept方法,即你可以写
Consumer<Object> c = /* some expression producing it*/;
c.accept(new JButton());
// or just
c.accept(new Object());
Run Code Online (Sandbox Code Playgroud)
因为你不能写
foo(new JButton());
// or
foo(new Object());
Run Code Online (Sandbox Code Playgroud)
当你只有a foo(int)和a时foo(String),它也是不可能的
Consumer<Object> c = OverloadingMethodRef::foo;
Run Code Online (Sandbox Code Playgroud)
这将构造一个Consumer假装接受任意Object实例.
如果您愿意接受Reflection开销,则可以使用
Consumer<Object> c=o -> {
try {
new Statement(OverloadingMethodRef.class, "foo", new Object[]{o}).execute();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
};
c.accept(42);
c.accept("bla");
Run Code Online (Sandbox Code Playgroud)
(这是指java.beans.Statement)
当然,在使用不受支持的参数类型调用时,这可能会在运行时失败.
| 归档时间: |
|
| 查看次数: |
1772 次 |
| 最近记录: |