本文介绍了如果我不想在Kotlin中使用卑鄙的类调用基类的构造函数,该怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以创建Derived的实例,但不能调用Base的构造函数?

Is there any way to create an instance of Derived but not call the constructor of Base?

open class Base(p: Int)

class Derived(p: Int) : Base(p)

推荐答案

您实际上可以做到

import sun.misc.Unsafe

open class Base(p: Int){
    init {
        println("Base")
    }
}

class Derived(p: Int) : Base(p){
    init {
        println("Derived")
    }
}

fun main() {
    val unsafe = Unsafe::class.java.getDeclaredField("theUnsafe").apply {
        isAccessible = true
    }.get(null) as Unsafe

    val x = unsafe.allocateInstance(Derived::class.java)

    println("X = $x")
}

但是请不要这样做,该解决方案是一种低级机制,旨在仅由核心Java库而不是标准用户使用.如果使用它会破坏OOP的逻辑.

But don't, this solution is a low-level mechanism that was designed to be used only by the core Java library and not by standard users. You will break the logic of OOP if you use it.

这篇关于如果我不想在Kotlin中使用卑鄙的类调用基类的构造函数,该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 14:45