本文介绍了如何从不同的模块隐藏Java中的Kotlin内部类的可见性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用我在Kotlin中开发的Android库.我将某些类的访问修饰符保留为internal.内部类仅在Kotlin的该库模块中可见.如果我在应用程序中实现该库,那么它根本不可见.

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.

但是从Java代码访问该库时出现问题.如果我创建.java文件并键入该库的internal类的名称,则IDE会建议使用该名称,并且将对其进行解析和编译,而不会出现任何错误.

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.

例如

internal class LibClass {
    // Fields and Methods
}


DemoApp模块中实现上述库之后:


After implementing above library in DemoApp module:

fun stuff() {
    val lib = LibClass() // Error.. Not resolving
}

Java的:

public void stuff() {
    LibClass lib = new LibClass() // Successfully resolving and compiling
}

这就是问题所在.如何从Java保护该类?

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

谢谢!

推荐答案

不是完美的解决方案,但我发现了两个hacky解决方案

Not perfect solution but I found two hacky solutions

例如

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.

例如

internal class LibClass {

    @JvmSynthetic
    fun foo() {}

    @JvmSynthetic
    fun bar() {}
}

注意:

此解决方案保护该函数的方法/字段.按照问题,它不会隐藏Java中类的可见性.因此,仍在等待完美的解决方案.

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.

这篇关于如何从不同的模块隐藏Java中的Kotlin内部类的可见性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 05:53