我在Java中有这个抽象类:

abstract class AbsApiTestCase<T> {
    T mApi;

    @Before
    public void setUp() throws Exception {
        mApi = instanceApi((Class<T>) (
                  (ParameterizedType) getClass().getGenericSuperclass())
                     .getActualTypeArguments()[0]);
    }

    static <T> T instanceApi(Class<T> clazz) throws Exception {
        return new Retrofit.Builder()
            .baseUrl(clazz.getField("BASE_URL").get(null).toString())
            .addConverterFactory(GsonConverterFactory.create(
                    new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create()))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .client(getClient())
            .build().create(clazz);

    }
    // some code
}

api看起来像这样:
public interface GithubApi {
    String BASE_URL = "https://api.github.com/";
    // some code
}

可以这样使用:
public class GithubApiTest extends AbsApiTestCase<GithubApi> {
    // some code
}

但是,当我将代码转换为kotlin时,静态字段BASE_URL看起来像这样:
interface GithubApi {
    companion object {
        val BASE_URL = "https://api.github.com/"
    }
    // some code
}

不能像上面那样访问BASE_URL。我发现这里有一个@JvmField批注,但是Android studio说JvmField cannot be applied to a property defined in companion object of interface

有没有办法访问此“静态字段”?

最佳答案

如何将BASE_URL设为编译时常量?

interface GithubApi {
    companion object {
        const val BASE_URL = "https://api.github.com/"
    }
}

在字节码级别,BASE_URLGithubApi接口(interface)的静态字段。
public interface GithubApi {
  public static final GithubApi$Companion Companion;

  public static final java.lang.String BASE_URL;

  static {};
    Code:
       0: new           #26                 // class GithubApi$Companion
       3: dup
       4: aconst_null
       5: invokespecial #30                 // Method GithubApi$Companion."<init>":(Lkotlin/jvm/internal/DefaultConstructorMarker;)V
       8: putstatic     #32                 // Field Companion:LGithubApi$Companion;
      11: return
}

09-28 06:31