据我所知,随着Java 7中MethodHandle的引入,编译器生成的方法重载也随之引入。
MethodHandle的javadoc(我已经删减了示例)说明如下:
我听说MethodHandles正在为Java 8中的lambda等功能做准备。(我知道它们已经对脚本语言很有用了。)
[/介绍]
那么,在Java中是否还有更多这些编译器生成的重载隐藏着?在未来会有更多的提示(比如扩展方法)吗?首先为什么需要它?仅仅是为了速度吗?它如何帮助lambda(我以为lambda会编译成匿名内部类)?
简而言之,它们(生成的重载)现在和将来为什么有用?
更新:我在这里所说的编译器生成的重载,Oracle的人称之为签名多态。
MethodHandle的javadoc(我已经删减了示例)说明如下:
实际上,invokeExact和相关方法的行为就像每个可能的参数组合和返回类型都有一个重载一样。Here are some examples of usage:
Object x, y; String s; int i; mh = ... // (Ljava/lang/String;CC)Ljava/lang/String; // (String, char, char) -> String s = (String) mh.invokeExact("daddy",'d','n'); // (Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; // (Object, Object, Object) -> Object x = mh.invokeExact((Object)1, (Object)2, (Object)3); // (Ljava/util/List;)I // (List) -> int i = (int) mh.invokeExact(java.util.Arrays.asList(1,2,3)); // (Ljava/io/PrintStream;Ljava/lang/String;)V // (PrintStream, String) -> void mh.invokeExact(System.out, "Hello, world.");
Each of the above calls generates a single invokevirtual instruction with the name invoke and the type descriptors indicated in the comments. The argument types are taken directly from the actual arguments, while the return type is taken from the cast immediately applied to the call. This cast may be to a primitive. If it is missing, the type defaults to Object if the call occurs in a context which uses the return value. If the call occurs as a statement, a cast is impossible, and there is no return type; the call is void.
我听说MethodHandles正在为Java 8中的lambda等功能做准备。(我知道它们已经对脚本语言很有用了。)
[/介绍]
那么,在Java中是否还有更多这些编译器生成的重载隐藏着?在未来会有更多的提示(比如扩展方法)吗?首先为什么需要它?仅仅是为了速度吗?它如何帮助lambda(
简而言之,它们(生成的重载)现在和将来为什么有用?
更新:我在这里所说的编译器生成的重载,Oracle的人称之为签名多态。