2016-04-15 28 views
0

我想通過將方法傳遞給方法set_Execute.Can來設置一個布爾值爲true。有人可以幫助解決這個問題嗎?無法通過在方法內調用變量來將值設置爲

這裏是代碼:

public boolean canExecute(){ 
    boolean execute=false; 
    set_Execute(execute); 
    log("can execute"+execute); //it is going inside method set_Execute but it is always printing execute as false 
    return execute; 
    } 

    private boolean set_Execute(boolean setExecute){ 
    return setExecute=true; 
    } 
+1

@ ritesht93這絕對沒有區別。 '布爾'是不可變的。 – Radiodef

+0

不,我通過那個帖子,但沒有得到確切的答覆,並且它說abt傳遞參考或value.mine是不同的 – divya

+1

它不是。完全一樣。 – Savior

回答

0

布爾在Java中是不可變的包裝,使他們不能設置。如果您希望能夠編輯方法中的內部值,您可以使用AtomicBoolean

public boolean canExecute(){ 
    AtomicBoolean execute = new AtomicBoolean(false); 
    set_Execute(execute); 
    log("can execute" + execute.get()); 
    return execute.get(); 
} 

private void set_Execute(AtomicBoolean setExecute) { 
    setExecute.set(true); 
} 
+1

請不要混淆不變性和變量賦值。他們的例子不會失敗,因爲任何事物都是不可變的 – Savior

0

你不能直接做你想做的事情,因爲,正如Pillar解釋的,Java通過值傳遞變量,而不是通過引用。所以方法參數的改變永遠不會傳回給調用者。

對類的實例的引用也是按值傳遞的,但引用仍然指向與調用者看到的實例相同的實例,所以一個好的解決方案是將您的執行標誌封裝在類中並進行操作在它的一個實例上。 這樣你可以改變實例內的值。

在您的情況下,您的旗幟代表權限,因此創建類別Permission是有意義的。

我已經將剩下的代碼保留了,但根據應用程序的整體架構,將set_Execute方法也編入Permission類也許有意義。

public class Permission { 
    private boolean allowed; 

    public void setAllowed(boolean allowed) { 
     this.allowed = allowed; 
    } 

    // Add getAllowed and toString methods 
} 
public Permission canExecute(){ 
    Permission execute = new Permission(); 
    set_Execute(execute); 
    log("can execute"+execute); //it is going inside method set_Execute but it is always printing execute as false 
    return execute; 
} 

private void set_Execute(Permission setExecute){ 
    setExecute.setAllowed(true); 
} 
1

你應該重新設置爲執行像下面的值。

execute = set_Execute(execute);