java - 无法从主项目访问变量?
问题描述
我无法hi
从我的库类中访问该变量。为什么?一探究竟:
我的库中有这个接口:
interface ContextAccessor {
fun getApplicationContext(): Application?
}
还有这段代码:
class SomeLibraryClass {
private var mContextAccessor: ContextAccessor?
String extractedHi = null
fun setContextAccessor(contextAccessor: ContextAccessor?) {
mContextAccessor = contextAccessor
}
fun someOtherMethod() {
mContextAccessor?.getAppContext()?.let { nonNullContext ->
// use nonNullContext here
extractedHi = nonNullContext.hi; // i get error here!
}
}
}
我的项目中的这个类:
public class MyActivity extends Activity implements MyActivity.ContextAccessor {
private SomeLibraryClass someLibraryClassInstance = SomeLibraryClass();
public String hi = "hi";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ContextAccessor reference is set to some library class
someLibraryClassInstance.setContextAccessor(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
// Super important!
someLibraryClassInstance.setContextAccessor(null);
// OR create some method like `someLibraryClassInstance.removeContextAccessor(this)`
}
@Override
public Application getApplicationContext() {
return super.getApplication();
}
}
解决方案
hi
向ContextAccessor
接口添加属性:
interface ContextAccessor {
val hi: String
// ...
}
在MyActivity
实现getHi()
方法中:
@NotNull
@Override
public String getHi() {
return hi;
}
在您的库类SomeLibraryClass
中,您可以像下面这样访问它:
var extractedHi: String? = null
fun someOtherMethod() {
extractedHi = mContextAccessor?.hi
}
推荐阅读
- asp.net - 如何从 ASP.NET 中的路由路径中删除页面 URL?
- .net - Entity Framework Core 中的 db.Entry 与 db.update
- javascript - Angular Material Sidenav 只会显示导航列表中的第一项
- html - 禁用下载链接(使用 HTML5 下载属性)直到下载完成
- codeigniter - 我的匹配规则 codeigniter 不适用于我输入的字符串
- java - 如何在 Java 中为 Okttp 编写 Junit Mockito 测试
- dacpac - 使用 AAD MFA 身份验证使用 SqlPackage.exe (DACPAC) 发布的命令是什么?
- vue.js - 点击事件后函数触发,但不更新 VueJS 中的数据变量
- python-3.x - 在 Python 中解析字符串
- sql - 获取最新记录,字段可以为空