且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我怎样才能只开班考试呢?

更新时间:2023-02-04 22:36:39

在形式上,不可能在JVM上诚实地做到这一点,因为无法为可能的干预者的子集打开类.

Formally it is not possible to do this honestly on JVM, because class couldn't be open for subset of possible interiters.

但是,可以通过以下技巧部分完成它:

However it can be partially done by the following trick:

open class SomeClass internal constructor(val configurableParameter: Int) {
    companion object {
        private const val defaultInput = 123

        fun create() = SomeClass(defaultInput)
    }
}

只能从同一模块(或从测试)调用此类的构造函数.而且班级是公开的,所以任何人都可以使用它.但是,从外部模块中,只有两种构建类的方法:伴随对象或反射.

The constructor of this class can be called only from the same module (or from tests). And class is public, so anyone can use it. However from external modules you have only two ways of the class construction: companion object or reflection.

最后,由于构造函数是内部的,因此您无法在任何其他模块上继承此类.

And finally you couldn't inherit from this class at any other modules, because constructor is internal.