How to hide visibility of Kotlin internal class in Java from different modules?

拜拜、爱过 提交于 2020-08-06 05:53:07

问题


I was working on the Android library which I'm developing in Kotlin. I kept access modifier of some classes as internal. Internal classes are only visible in that library module in Kotlin. If I implement that library in the app then it's not visible at all.

But the problem comes when accessing that library from Java code. If I create .java file and type name of that internal class of library then IDE is suggesting name and it's resolved and compiled without any error.

For e.g.

Library Module:

internal class LibClass {
    // Fields and Methods
}

After implementing above library in DemoApp module:

App Module

Kotlin:
fun stuff() {
    val lib = LibClass() // Error.. Not resolving
}
Java:
public void stuff() {
    LibClass lib = new LibClass() // Successfully resolving and compiling
}

So that's the problem. How can I achieve securing that class from Java?

Thank you!


回答1:


I see you have got class with internal modifier that cannot be instantiated in kotlin class but can be instantiated in Java file. If it’s a standalone class, you can make its constructor private and allow the instantiation using a static method (Companion object).




回答2:


Not perfect solution but I found two hacky solutions

Annotate every public method of that internal class by @JvmName with blank spaces or special symbols by which it'll generate syntax error in Java.

For e.g.

internal class LibClass {

    @JvmName(" ") // Blank Space will generate error in Java
    fun foo() {}

    @JvmName(" $#") // These characters will cause error in Java
    fun bar() {}
}

Since this above solution isn't appropriate for managing huge project or not seems good practice, this below solution might help.

Annotate every public method of that internal class by @JvmSynthetic by which public methods aren't accessible by Java.

For e.g.

internal class LibClass {

    @JvmSynthetic
    fun foo() {}

    @JvmSynthetic
    fun bar() {}
}

Note:

This solution protects the methods/fields of the function. As per the question, it does not hide the visibility of class in Java. So the perfect solution to this is still awaited.



来源:https://stackoverflow.com/questions/62937511/how-to-hide-visibility-of-kotlin-internal-class-in-java-from-different-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!