本文介绍了如何在kotlin中使用reflect访问静态字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中有这个抽象类:

I have this abstract class in 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看起来像这样:

And api looks like this:

public interface GithubApi {
    String BASE_URL = "https://api.github.com/";
    // some code
}

它可以这样使用:

public class GithubApiTest extends AbsApiTestCase<GithubApi> {
    // some code
}

但是当我将代码转换为kotlin时,静态字段BASE_URL看起来像这样:

But when I convert my code to kotlin, the static field BASE_URL looks like this:

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.

And BASE_URL cannot be accessed like above. I found there is a @JvmField annotation but Android studio says JvmField cannot be applied to a property defined in companion object of interface.

是否可以访问此静态字段"?

Is there a way to access this "static field"?

推荐答案

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

How about making BASE_URL a compile-time constant?

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

在字节码级别,BASE_URLGithubApi接口的静态字段.

At byte-code level BASE_URL is a static field of the GithubApi 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
}

这篇关于如何在kotlin中使用reflect访问静态字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 19:08