可以脱离其他班级吗?
我最近重新发现了打破标签的用途。现在我想知道是否可以重新使用另一个类的标签。
我想要的示例:
Main.class
label:
for (Product p : ProductList) {
if (p.getSet() == true) {
classHandler();
}
}
Classhandler.class
someFunction() {
break label;
}
当我输入此内容时,我实际上尝试在我的 Main
类中创建一个本地函数(这样我就可以调用该函数),但即使在那里我也得到了未定义的标签:标签
错误。
I recently rediscovered the use of breaking back to a label. Now I'm wondering if it is possible to break back to a label from another class.
Example of what i want:
Main.class
label:
for (Product p : ProductList) {
if (p.getSet() == true) {
classHandler();
}
}
Classhandler.class
someFunction() {
break label;
}
While I was typing this I actually tried making a local function in my Main
class (so I could just call that function instead) but even there I got the undefined label: label
error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,你不能。而你不应该。
如果中断的条件存在问题,那么抛出异常将是正确的方法。
否则,您应该执行一些操作,例如返回一个标志,指示是否仍应处理其他产品并在循环中对其做出反应。
正如您所注意到的,您甚至无法
突破
方法边界,这是一件好事。break
和continue
是强大的工具,但如果使用错误的话,很容易使代码变得混乱。例如,隐藏在巨大代码块中的break
可能很容易被错过,但如果您在方法的最顶部使用continue
来跳过基于某些内容的迭代条件的话,意图就很明确了。No, you can't. And you shouldn't.
If the condition for breaking is some problem, then throwing an exception would be the correct approach.
Otherwise you should do something like returning a flag that indicates if other products should still be handled and reacting on that in your loop.
As you noticed you can't even
break
through method-borders, and that's a good thing.break
andcontinue
are powerful tools, but can easily make your code confusing, if used in the wrong way. For example abreak
hidden inside a huge code block can be easy to miss, but if you use acontinue
at the very top of a method to skip an iteration based on some condition, then the intention is pretty clear.您中断的标签必须在范围内。来自java sun文档:
The label that you break to must be in scope. From the java sun documentation:
不,你不能。这甚至在同一类的两个方法之间不起作用。标签的范围(最多)在单个方法内。
No, you cannot. That does not even work between two methods of the same class. Labels are scoped (at the most) within a single method.
这是没有意义的,因为不能保证标签存在,甚至不能保证在循环内调用 someFunction() 。
It doesn't make sense, since there is no guarantee that label exists, not even that someFunction() is called within a loop.