How to change a variable from a method
This question is a common issue, and I have tried to look at some thread as Is Java "pass-by-reference&qu开发者_如何学编程ot; or "pass-by-value"? or How to change an attribute of a public variable from outside the class but in my case I need to modify a boolean variable, with a Singleton instance.
So far I have a class, and a method which changes the boolean paramter of the class. But I would like to separate this mehod in a manager. The scheme is something like:
public class Test{
private boolean b;
public String getb(){}
public void setb(){}
String test = ClassSingleton.getInstance().doSomething();
}
public class ClassSingleton{
public String doSomething(){
//here I need to change the value of 'b'
//but it can be called from anyclass so I cant use the set method.
}
}
Thanks, David.
If I understand your requirement - this can solve your problem:
public interface IUpdatable
{
public void setB(boolean newValue);
}
public class Test implements IUpdatable
{
private boolean b;
public String getb(){}
public void setB(boolean newValue) {this.b = newValue;}
}
public class ClassSingleton
{
public String doSomething(IUpdatable updatable)
{
updatable.setB(true);
...
}
}
This way the Singleton
does not need to know your Test
class - it just knows the interface IUpdatable
that supports setting the value of B
. Each class that needs to set its B
field can implement the interface and the Singleton
can update it and remain oblivious to its implementation.
You could extract
public void setb(){}
into an interface (let's call itBSettable
), makeTest
implementBSettable
, and pass an argument of typeBSettable
intodoSomething
.Alternatively, you could make
b
into anAtomicBoolean
and makedoSomething
accept (a reference to) anAtomicBoolean
.
Define b as static variable.
Then call Test.b = value
Perhaps:
public class Test {
private static boolean b;
public static String getB() {}
public static void setB() {}
}
should help? Static fields and methods can be called without an instance (i.e. Test.setB();
).
I think your question is not very clear and your sample code is really badly done. Do you actually mean something like this?
public class Test{
private boolean b;
public boolean getb(){return b;}
public void setb(boolean b){this.b = b;}
String test = ClassSingleton.getInstance().doSomething(this);
}
public class ClassSingleton{
private static ClassSingleton __t__ = new ClassSingleton();
private ClassSingleton() {}
public String doSomething(Test t){
t.setb(true);
return null;
}
public static ClassSingleton getInstance(){
return __t__;
}
}
Do you mean your manager is a singleton? or your test class should be singleton? Please be more specific
精彩评论