Java中的Kotlin内部类公开可见

pri*_*ank 4 java android class public kotlin

我正在Kotlin 开发一个Android 密码库。我有几个internal类在Java应用程序中公开可见。在文档中找到了这一点

internal声明成为publicJava。internal类的成员会经历名称重整,这使得从Java中意外使用它们变得更加困难,并且允许重载具有相同签名且根据Kotlin规则彼此不可见的成员。

有办法解决这个问题吗?

hol*_*ava 5

我已经看到您所有的内部类都涉及加密解密

您可以通过定义一个顶级函数并将其标记为 @JvmSynthetic,然后将ECryptSymmetricDecryptECryptSymmetricEncrypt类设为私有来防止Java客户端访问您的内部类,从而轻松实现此目的,例如:

// define this top-level function in your ECryptSymmetricEncrypt.kt

@JvmSynthetic internal fun <T> encrypt(
                                       input:T, password: String, cipher:Cihper, 
                                       erl: ECryptResultListener, outputFile:File,
                                       getKey:(String,ByteArray)->SecretKeySpec){

  ECryptSymmetricEncrypt(input, password, cipher,
                { pass, salt -> getKey(pass, salt) }, erl, outputFile)
}
Run Code Online (Sandbox Code Playgroud)

但是,它解决了您的问题,但是我仍然要说,您的代码可以进一步细分。例如,加密和解密算法有很多重复项,也许您可​​以在加密库中应用模板方法模式,并引入接口以使您的库显式并Cipher在实现类下隐藏操作。理想情况下,客户端代码无法java.security.*通过EncryptDecrypt接口看到任何类。例如:

interface Encrypt{
   //          v--- don't include the infrastructure class here,e.g:`Keys`,`Cipher`
   fun encode(...args)
}

interface Decrypt{
   //          v--- don't include the infrastructure class here,e.g:`Keys`,`Cipher`
   fun decode(...args)
}
Run Code Online (Sandbox Code Playgroud)

它是您创建一个实例和计算结果是坏事init这里

并且您可以使用Factory Method Pattern避免在ECryptSymmetricDecryptECryptSymmetricEncrypt类中进行类型检查。


ice*_*000 5

除了@JvmSynthetic,您还可以使用@JvmName非法的 Java 标识符,例如添加空格。

例如,我在@JvmName参数中添加了一个空格,因此除 Kotlin 之外的任何语言都无法调用您的方法:

@JvmName(" example")
internal fun example() {
}
Run Code Online (Sandbox Code Playgroud)

  • 这看起来很糟糕,但聪明且技术上解决了如此高票的问题;) (2认同)