2016-04-15 26 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);