有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

安卓如何从java测试代码访问内部属性

我有一个属性标记为内部的类。 然后我尝试从java中的测试代码中设置该属性。 我如何访问这些属性?测试代码和类代码在同一个包中

例如:

class MainActivity : AppCompatActivity() {
    interal var someProperty = "test"
}

测试代码:

@Test
public void firstStartTest() {
    val activity = MainActivity() 
    activity.setSomeProperty("something") //does not compile

}

安卓工作室建议进行活动。为模块应用程序()设置某些属性$production\u sources\u; 但这也无法编译


共 (3) 个答案

  1. # 1 楼答案

    两个类(MainActivity和test类)必须在一个模块中。这是一个模块定义:

    More specifically, a module is a set of Kotlin files compiled together:

    • an IntelliJ IDEA module;
    • a Maven or Gradle project;
    • a set of files compiled with one invocation of the Ant task.

    https://kotlinlang.org/docs/reference/visibility-modifiers.html

    这意味着,检查你的项目结构

  2. # 2 楼答案

    添加@JvmField注释。 它将变量视为受java保护的

  3. # 3 楼答案

    有两种方法可以做到这一点:

    • 使属性protected。注意Java&;Kotlin以不同的方式对待protected。在Java中,同一个包中的其他类可能访问protected成员。因此,您的测试类(Java)可以访问它
    • 通过其丑陋的名称访问该房产。它应该有点像activity.setSomeProperty$production_...。使用自动完成。从the documentation

      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;