Kotlin:我如何在Java中使用委托属性?

Jir*_*ire 6 java delegates delegation kotlin delegated-properties

我知道你不能在Java中使用委托属性语法,并且不会像在Kotlin中那样"覆盖"set/get运算符,但我仍然希望在Java中使用现有的属性委托.

例如,int的简单委托:

class IntDelegate {
    operator fun getValue(thisRef: Any?, property: KProperty<*>) = 0
}
Run Code Online (Sandbox Code Playgroud)

在Kotlin当然我们可以这样使用:

val x by IntDelegate()
Run Code Online (Sandbox Code Playgroud)

但是我们如何IntDelegate在Java中以某种形式使用?这是开始,我相信:

final IntDelegate x = new IntDelegate();
Run Code Online (Sandbox Code Playgroud)

然后直接使用这些功能.但是我该如何使用该getValue功能呢?我的参数是什么?我如何获得KPropertyJava字段?

Ily*_*lya 5

如果您确实想了解 Kotlin 委托属性在 Java 中的底层情况,请看这里:在此示例中,xJava 类的属性JavaClass被委托给Delegates.notNull标准委托。

// delegation implementation details
import kotlin.jvm.JvmClassMappingKt;
import kotlin.jvm.internal.MutablePropertyReference1Impl;
import kotlin.jvm.internal.Reflection;
import kotlin.reflect.KProperty1;

// notNull property delegate from stdlib
import kotlin.properties.Delegates;
import kotlin.properties.ReadWriteProperty;


class JavaClass {
    private final ReadWriteProperty<Object, String> x_delegate = Delegates.INSTANCE.notNull();
    private final static KProperty1 x_property = Reflection.mutableProperty1(
            new MutablePropertyReference1Impl(
                JvmClassMappingKt.getKotlinClass(JavaClass.class), "x", "<no_signature>"));

    public String getX() {
        return x_delegate.getValue(this, x_property);
    }

    public void setX(String value) {
        x_delegate.setValue(this, x_property, value);
    }
}

class Usage {
    public static void main(String[] args) {
        JavaClass instance = new JavaClass();
        instance.setX("new value");
        System.out.println(instance.getX());
    }
}
Run Code Online (Sandbox Code Playgroud)

不过,我不建议使用此解决方案,不仅因为需要样板,而且因为它严重依赖于委托属性和 kotlin 反射的实现细节。