超类方法的引用方法

如何使用方法引用来引用超类方法?

在Java 8中,您可以执行SubClass.super::method

Kotlin的语法是什么?

期待你的回复!

结论

感谢Bernard Rocha! 语法是SubClass::method

不过要小心。 在我的情况下,子类是一个泛型类。 不要忘记宣布这样的:

MySubMap<K, V>::method

编辑

它在Kotlin仍然不起作用。

她是一个超级类方法引用的Java 8中的例子:

 public abstract class SuperClass { void method() { System.out.println("superclass method()"); } } public class SubClass extends SuperClass { @Override void method() { Runnable superMethodL = () -> super.method(); Runnable superMethodMR = SubClass.super::method; } } 

我还是无法在Kotlin做同样的事情…

编辑

这是我在Kotlin试图实现的一个例子:

 open class Bar { open fun getString(): String = "Hello" } class Foo : Bar() { fun testFunction(action: () -> String): String = action() override fun getString(): String { //this will throw an StackOverflow error, since it will continuously call 'Foo.getString()' return testFunction(this::getString) } } 

我想有这样的事情:

 ... override fun getString(): String { //this should call 'Bar.getString' only once. No StackOverflow error should happen. return testFunction(super::getString) } ... 

结论

在Kotlin中这样做是不可能的。

我提交了一份特写报告。 可以在这里找到: KT-21103方法参考超级方法

正如文档所说,你使用它像在java中:

如果我们需要使用类的成员或扩展函数,则需要合格。 例如String :: toCharArray给了我们一个类型为String:String。() – > CharArray的扩展函数。

编辑

我认为你可以做到你想做的事情是这样的:

 open class SuperClass { companion object { fun getMyString(): String { return "Hello" } } } class SubClass : SuperClass() { fun getMyAwesomeString(): String { val reference = SuperClass.Companion return testFunction(reference::getMyString) } private fun testFunction(s: KFunction0<String>): String { return s.invoke() } } 

根据贝尔纳多的回答,你可能有这样的事情。 它没有显着的变化。

 fun methodInActivity() { runOnUiThread(this::config) } fun config(){ } 

更重要的是,在传入的1.2版本中,你可以使用

 ::config 

您可以使用Java反射,如您已经建议:

 "string"::class.java.superclass.methods.forEach (::println) 

科特林的方式:

 5::class.superclasses.first().members.forEach(::println) 

不知道是否有可能获得对超类功能的引用,但是这是你想要实现的另一种选择:

 override fun getString(): String = testFunction { super.getString() }