A goto statement in C and its counterparts are accompanied by a Label argument. In a defined method, a goto label;
statement will fire the routine proceeding the label. Below is an example demonstrated by Greg Rogers in this Post.
void foo()
{
if (!doA())
goto exit;
if (!doB())
goto cleanupA;
if (!doC())
goto cleanupB;
// everything succeed
return;
cleanupB:
undoB();
cleanupA:
undoA();
exit:
return;
}
A goto
can be a very effective tool in Java, but Java does not explicitly support the goto
keyword even though the keyword has been reserved by the language. Using a break statement will enable the command jump out of the label to proceed to the statement after the label.
Example:
public class Klass {
public static void main(String[] args) {
// code goes here...
__main:
{
if(args.length==0)
{
break __main;
}
}
//code after label
}
}
The package com.sun.org.apache.bcel.internal.generic.GOTO
, I have not used it personally but I think it can aid to achieve the same code structure as demonstrated by Greg Rogers like this:
void foo()
{
if (!doA())
GOTO exit;
if (!doB())
GOTO cleanupA;
if (!doC())
GOTO cleanupB;
// everything succeed
return;
cleanupB:
undoB();
cleanupA:
undoA();
exit:
return;
}
void undoB(){}
void undoA(){}
boolean doC(){return false;}
boolean doA(){return false;}
boolean doB(){return false;}