我正在使用带有实例引用的自定义View类作为编辑器.视图仅用于片段.我需要实例引用,所以我总是可以获得自定义View的自定义参数.
public static StoryView instance;
private Story story;
public static Story getCurrentStory(){
if(instance == null) return null;
else return instance.story;
}
Run Code Online (Sandbox Code Playgroud)
但是,当我使用此getter方法更改Navigation Drawer的内容时,我收到一条警告:
在这里:
private static IDrawerItem[] drawerEditorItems(){
Story s = StoryView.getCurrentStory();
SectionDrawerItem section_editor = new SectionDrawerItem()
.withName(str("placeholder_story_by", s.name, s.author))
.withDivider(false);
return new IDrawerItem[]{ section_editor };
}
Run Code Online (Sandbox Code Playgroud)
str(String id, Object... args) 是一种静态方法,基本上格式化i18n字符串.
我的猜测是,在s函数范围的末尾可能通过赋值来销毁引用s = null?也许这可能会破坏instance.story我的自定义View中的实际内容?
你打电话的时候
public static Story getCurrentStory(){
if(instance == null) return null;
else return instance.story;
}
Run Code Online (Sandbox Code Playgroud)
您检查以确保实例不为空.如果是,则返回null.这里的情况可能是实例始终为null(从未初始化).这意味着如果要获取当前故事,必须确保在调用实例之前初始化实例.
而且,这在技术上不是必需的.返回null实例等同于检查它是否为null,然后返回null.您还可以使用@NotNull和@Nullable帮助编译器,您自己以及其他任何处理代码/与之交互的人.
此外,在某些情况下它仍可能返回null,因此您需要添加一个检查以确保它不为null.这可以使用if语句完成:
if(s != null){
//Do whatever
}
Run Code Online (Sandbox Code Playgroud)
但是你得到这个警告的原因是(根据我的经验)几乎可以肯定你会得到一个例外.以此为例:
View v = null;
v.setText("");
Run Code Online (Sandbox Code Playgroud)
这显示了与您相同的警告.因此,最有可能的是,无论如何,您的方法都将返回null.所以你必须确保instance初始化,并有一个if语句,以确保应用程序不会崩溃,如果它是null.初始化instance是一种确保获得非null引用的方法