我有这个抽象类中的java:如何访问反映kotlin的静态字段?
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
。
有没有办法访问这个“静态字段”?
你如何计划使用'GithubApi'?你需要从Java访问吗? – voddan
@voddan不,我只需要一个url值来创建实例,而我无法在'KClass .members'中找到它' –
user6238994