java – 我在尝试编写if条件时收到死代码警告
发布时间:2020-12-15 04:14:40 所属栏目:Java 来源:网络整理
导读:我收到了代码的死代码警告: Topic topic = findTopicByID(point.getIDTopic());if (topic != null){ ...}else if (topic == null){ // I get Dead code warning for every thing I write here!} 有时当我收到警告但一切看起来都没问题时,我重新启动IDE并且
我收到了代码的死代码警告:
Topic topic = findTopicByID(point.getIDTopic()); if (topic != null) { ... } else if (topic == null) { // I get Dead code warning for every thing I write here! } 有时当我收到警告但一切看起来都没问题时,我重新启动IDE并且我不再收到警告了!但这一次…… 编辑: public Topic findTopicByID(int IDTopic) { for (Topic topic : topics) if (topic.getID() == IDTopic) return topic; return null; } 编辑: Topic topic = Res.getSchedule().getTopicBox().findTopicByID(point.getIDTopic()); Section section = topic.findSectionByID(point.getIDSection()); if (topic != null) { View rowView = inflater.inflate(R.layout.daily_day_day_row,lLDoneWorks,false); TextView tVLabel = (TextView) rowView.findViewById(R.id.daily_day_day_row_label); TextView tVNum = (TextView) rowView.findViewById(R.id.daily_day_day_row_num); TextView tVTopic = (TextView) rowView.findViewById(R.id.daily_day_day_row_topic); TextView tVSection = (TextView) rowView.findViewById(R.id.daily_day_day_row_section); int color = topic.getColor(); tVLabel.setBackgroundColor(color); tVNum.setTextColor(color); tVTopic.setTextColor(color); tVSection.setTextColor(color); tVLabel.setText(topic.getName().substring(0,1).toUpperCase(Locale.US)); tVNum.setText(Integer.toString(point.getCount())); tVTopic.setText(topic.getName()); if (point.getIDSection() != Point.DEFAULT_SECTION) tVSection.setText(section.getName()); lLDoneWorks.addView(rowView); } else if (topic == null) { TopicArchived archivedTopic = Res.getSchedule().getTopicBox() .findArchivedTopicByID(point.getIDTopic()); if (archivedTopic == null) removedTopicsPoint += point.getCount(); else archivedTopicsPoint += point.getCount(); } 解决方法
这是因为这条线:
Section section = topic.findSectionByID(point.getIDSection()); 如果topic为null,则表示存在NullPointerException,并且未到达其余代码.因此,对事后出现的主题空值的每次检查都是无关紧要的:编译器知道主题在该行之后不为空. 您应该将该行放在if语句的第一个分支中. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |