Java中的Kotlin内部类公开可见 [英] Kotlin internal classes in Java visible publicly
问题描述
我正在Kotlin开发一个Android 密码库.我有几个internal
类,它们在Java应用程序中公开可见.在文档中找到此.
I am developing an Android crypto library in Kotlin. I have a couple of internal
classes which become publicly visible in a Java app. Found this in documentations.
internal
声明在Java中变为public
.internal
类的成员经过名称修饰,以使其更难从Java中意外使用它们,并允许重载具有相同签名且根据Kotlin规则彼此不可见的成员;
internal
declarations becomepublic
in Java. Members ofinternal
classes go through name mangling, to make it harder to accidentally use them from Java and to allow overloading for members with the same signature that don't see each other according to Kotlin rules;
有没有办法解决这个问题?
Is there a way to get around this?
推荐答案
I have seen all of your internal classes are all about encrypt & decrypt.
您可以通过定义一个顶级函数并将其标记为@JvmSynthetic
,然后使 ECryptSymmetricEncrypt 类设置为 private ,以防止Java客户端访问您的内部类,例如:
you can do it easily by define a top-level function and mark it as @JvmSynthetic
, and then makes the ECryptSymmetricDecrypt and ECryptSymmetricEncrypt classes to private to prevent Java client access your internal classes, for example:
// 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)
}
但是,它解决了您的问题,但是我仍然想说您的代码可以进一步细分.例如,加密和加密解密算法有很多重复项,也许您可以在您的加密库&中使用模板方法模式.引入接口以显式地创建您的库,并在实现类下隐藏Cipher
操作.理想情况下,客户端代码无法通过Encrypt
或Decrypt
接口看到任何java.security.*
类.例如:
However, it solved your problem, but I still want to say that your code can break into small pieces as further. for example, the encrypt & decrypt algorithm have many duplications, maybe you can applies Template Method Pattern in your encrypt library & introduce interfaces to make your library explicitly and hiding the Cipher
operations under the implementation classes. Ideally, the client code can't see any java.security.*
classes via Encrypt
or Decrypt
interfaces. for example:
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)
}
AND it is a bad thing that you create an instance and compute the result in init
block here.
AND ,您可以使用工厂方法模式来避免该类型检查 ECryptSymmetricEncrypt 类.
AND you can use Factory Method Pattern to avoid the type checking both in ECryptSymmetricDecrypt and ECryptSymmetricEncrypt classes.
这篇关于Java中的Kotlin内部类公开可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!