【问题标题】:"kotlin-noarg" plugin don't work in Realm“kotlin-noarg”插件在 Realm 中不起作用
【发布时间】:2017-08-19 07:26:09
【问题描述】:

“kotlin-allopen”插件工作,但“kotlin-noarg”插件不工作。 我该怎么办?

下面是代码。

build.gradle

buildscript {
    ext.kotlin_version = '1.1.3-2'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-beta2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-noarg:$kotlin_version"
        classpath "io.realm:realm-gradle-plugin:3.5.0"
    }
}
apply plugin: "kotlin-allopen"
apply plugin: "kotlin-noarg"

allOpen {
    annotation("sample.AllOpen")
}
noArg {
    annotation("sample.NoArg")
    invokeInitializers = true
}

app/build.gradle

apply plugin: 'realm-android'

NoArg.kt

@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.SOURCE)
annotation class NoArg

MyApplication.kt

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        Realm.init(this)
    }
}

AndroidManifest.xml

<application
    android:name=".MyApplication"

SampleEntity.kt

@NoArg
@AllOpen
@RealmClass
data class SampleEntity(var sample: String?) : RealmModel

编译时出现如下错误。Class "SampleEntity" must declare a public constructor with no arguments if it contains custom constructors.

它是否适用于领域?

【问题讨论】:

    标签: android realm kotlin


    【解决方案1】:

    这是预期的行为。来自文档:https://kotlinlang.org/docs/reference/compiler-plugins.html#no-arg-compiler-plugin

    生成的构造函数是合成的,所以不能直接调用 来自 Java 或 Kotlin,但可以使用反射调用它

    【讨论】:

    • 比你。我忽略了这一点。以下代码有效。 val entity = SampleEntity::class.java.newInstance()
    • 您应该使用 @NoArg 注释 SampleEntity,或将 @RealmClass 添加到 noArg 配置中
    • 看起来 Realm 在通过此类 github.com/realm/realm-java/blob/… 进行检查时特别需要 public 无参数构造函数(请参阅 isDefaultConstructor),这意味着合成构造函数将不起作用。注意,如果构造函数中的每个参数都有默认值,Kotlin 将生成一个公共的无参数构造函数。
    • 是否可以在调用 realm-annotations-processor 之前运行 no-arg ?由于isDefaultConstructor通过反射判断是否为Public,所以如果顺序发生变化似乎是可能的
    • 不可能 - 由 kotlin-noargs 创建的 no-args 构造函数只能通过反射调用的原因是因为它实际上是私有的,因此更改注释处理器的运行顺序不会不同。
    猜你喜欢
    • 2022-07-15
    • 2022-12-21
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    相关资源
    最近更新 更多