1

Section 15.13 of the Java Language Specification for Java 8 describes this form of the method reference syntax for creating a constructor reference:

    ClassType :: [TypeArguments] new

For example:

    String s = "abc";
    UnaryOperator<String> test0 = String::new; // String(String) constructor.
    String s0 = test0.apply(s);
    System.out.println("s0 = " + s0); // Prints "abc".

    char[] chars = {'x','y','z'};
    Function<char[], String> test1 = String::new; // String(char[]) constructor.
    String s1 = test1.apply(chars);
    System.out.println("s1 = " + s1); // Prints "xyz"

That all works fine, but it seems that absolutely anything (excluding primitives) can be also supplied for the [TypeArguments] and everything still works:

Here's a silly example to prove the point:

    Function<String, String> test2 = String::<LocalDateTime, Thread[]>new; // Compiles !!!???
    String s2 = test2.apply("123");
    System.out.println("s2 = " + s2); // Prints "123"

A few questions arising:

[1] Since the String class doesn't even use generics, is it valid that the compiler allows the creation of that test2 constructor reference with those meaningless [TypeArguments]?

[2] What would be a meaningful example of using [TypeArguments] when creating a constructor reference?

[3] Under what conditions is it essential to specify [TypeArguments] when creating a constructor reference?

4

1 に答える 1

5

1 15.13.1. メソッド参照のコンパイル時宣言

メソッド参照式の形式が ClassType :: [TypeArguments] new の場合、潜在的に適用可能なメソッドは、ClassType のコンストラクタに対応する概念的なメソッドのセットです。...

それ以外の場合、候補の概念上のメンバー メソッドは ClassType のコンストラクタであり、戻り値の型 ClassType を持つメソッドであるかのように扱われます。これらの候補の中から、§15.12.2.1 で指定されているように、適切なアクセシビリティ、アリティ (n)、および型引数のアリティ ([TypeArguments] から派生) を持つメソッドが選択されます。

JLS 15.12.2.1。潜在的に適用可能な方法を特定する

この句は、非ジェネリック メソッドが、明示的な型引数を提供する呼び出しに適用される可能性があることを意味します。確かに、それは適用されることが判明するかもしれません。このような場合、型引数は単純に無視されます。

2コンストラクターがパラメーター化されている場合。私はつまずいたことがありません。

public class Foo {

   public <T> Foo(T parameter) {
...
Function<String, Foo> test = Foo::<String>new

3コンパイラが型を推測できない場合。

于 2015-03-20T18:45:27.860 に答える