Java中的Kotlin内部类公开可见 [英] Kotlin internal classes in Java visible publicly

查看:125
本文介绍了Java中的Kotlin内部类公开可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在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 become public in Java. Members of internal 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,然后使

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操作.理想情况下,客户端代码无法通过EncryptDecrypt接口看到任何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)
}

并且,创建实例并在init

AND it is a bad thing that you create an instance and compute the result in init block here.

AND ,您可以使用工厂方法模式来避免该类型检查

AND you can use Factory Method Pattern to avoid the type checking both in ECryptSymmetricDecrypt and ECryptSymmetricEncrypt classes.

这篇关于Java中的Kotlin内部类公开可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆