0

Is it possible to get a reference to the constructor of an anonymous class?

For example:

void someMethod(Function<String, SomeInterface> factory)

could be used as:

someMethod(SomeClass::new)

or

someMethod(str -> new SomeInterface(){...});

In the second case I used a lambda expression but I want a function reference.

4

1 回答 1

3

不,你不能。

java教程

有四种方法引用:

  • 引用静态方法ContainingClass::staticMethodName
  • 引用特定对象的实例方法ContainingObject::instanceMethodName
  • 引用特定类型的任意对象的实例方法 ContainingType::methodName
  • 对构造函数的引用 ClassName::new

这些都不匹配匿名类构造函数。


如果你真的想要一个方法引用,你可以编写另一个方法并引用它:

SomeInterface createSomeInterface(String str) {
    return new SomeInterface(){...};
}

someMethod(this::createSomeInterface);
于 2014-08-08T17:05:22.190 回答