猿问

如何在kotlin中访问java类的静态变量?

例如:我首先有一个 java 类


首先.java


   `class First{

      public static TAG = "test"

    }`

第二.kt


  `class Second{

     First.TAG  /*Error classifier First does not have a companion object,and thus must be initialized here*/

   }`

所以帮我在Second.kt kotlin类中调用First.java中声明的静态变量TAG


哈士奇WWW
浏览 486回答 3
3回答

喵喵时光机

Java类:class First {&nbsp; &nbsp; public static String TAG = "test";}科特林类:class Second {&nbsp; &nbsp; val secondTag: String = First.TAG}没有问题。尝试使用 IntelliJ IDEAfun main(args: Array < String > ) {&nbsp; &nbsp; val s = Second()&nbsp; &nbsp; println(s.secondTag)}印刷 test

繁星coding

只需制作一个适当的静态最终常量即可。class First {&nbsp; &nbsp; &nbsp; public static final String TAG = "test"}现在您可以从 Kotlin 调用它。class Second {&nbsp; &nbsp;fun blah() {&nbsp; &nbsp; &nbsp; &nbsp;val tag = First.TAG&nbsp; &nbsp;}}

HUWWW

头等舱package com.your.packageobject First {&nbsp; &nbsp; val TAG: String= "Your TAG";}二等舱class Second{&nbsp; &nbsp; &nbsp;First.TAG&nbsp;&nbsp; &nbsp;}Kotlin 没有静态成员或成员函数,你可以使用伴随对象
随时随地看视频慕课网APP

相关分类

Java
我要回答