2012-05-07 38 views
2

假設你有一個Java代碼:的infame藤,爪哇,自動代碼

public class MyClass { 
    public static Object doSmthg(Object A,Object B){ 
     if(smthg){ //if is given has an example, it can be any thing else 
      doSmthg; 
      GOTO label; 
     } 
     doSmthg; 

     label; 
     dosmthg1(modifying A and B); 
     return an Object; 
    } 
} 

我自動生成的代碼。當發生器到達產生goto的時刻(並且它不知道它在if塊中)時,它不知道後面會發生什麼。

我試過使用標籤,打破,繼續,但這是行不通的。

我試圖使用一個內部類(做dosmthg1),但A和B必須聲明爲final。問題是A和B必須修改。

如果沒有其他解決方案,我將不得不在我的生成器中傳播更多的知識。但我更喜歡更簡單的解決方案。

任何想法?

在此先感謝。

+0

所以,你想在你的Java代碼生成器,實現了'GOTO'?爲什麼?爲什麼不使用'if-else'? – Thomas

回答

1
public static Object doSmthg(Object A,Object B){ 
    try { 
    if(smthg){ //if is given has an example, it can be any thing else 
     doSmthg; 
     throw new GotoException(1); 
    } 
    doSmthg; 

    } catch (GotoException e) { 
     e.decrementLevel(); 
     if (e.getLevel() > 0) 
      throw e; 
    } 
    dosmthg1(modifying A and B); 
    return an Object; 
} 

一個可以做異常的gotos,但是爲了定位正確的「標籤」,你必須檢查異常消息或者想到嵌套級別。

我不知道我是否覺得這不是醜陋的。

+0

這是相當醜陋的,是的,但也很有創意。 ;) – ZeroOne

+0

輝煌!每個功能只需要一個標籤。我必須承認使用例外來做到這一點從來沒有發生過。不好,我不能投你的帖子。 – rvlander

1

就可以在塊添加一個虛擬環路標籤前面,並用標籤break作爲goto語句的等價物:

public static Object doSmthg(Object A,Object B){ 
    label: 
    do { // Labeled dummy loop 
     if(smthg){ //if is given has an example, it can be any thing else 
      doSmthg; 
      break label; // This brings you to the point after the labeled loop 
     } 
     doSmthg; 
    } while (false); // This is not really a loop: it goes through only once 
    dosmthg1(modifying A and B); 
    return an Object; 
} 
+0

太棒了!非常感謝! – rvlander

1

如果你想跳過去的東西,就像這樣:

A 
if cond goto c; 
B 
c: C 

你可以做到這一點像

while (true) { 
    A 
    if cond break; 
    B 
} 
C 
+0

這只是繼續執行A,不好。 Dasblinkenlight有更好的解決方案:'do {...} while(false)'。 – ZeroOne

+0

如果goto已經在一個循環中(這裏以「if」爲例),此解決方案需要來自代碼生成器的知識。 – rvlander

+0

轉換爲fall-thru的情況下,如果(cond)break;'也適合。 –