Mutable boolean field in Java

前端 未结 9 2123
挽巷
挽巷 2020-12-09 07:32

I need a mutable boolean field in Java (I will return this field via get* method later and it should be possible to modify this field).

Boolean doesn\'t work because

相关标签:
9条回答
  • 2020-12-09 08:12

    Are you really saying that you want callers to be able to modify the object's boolean value by manipulating what gets returned? So that the object and caller would share a reference to it?

    Just so I understand, given:

    class OddClass {
       private Boolean strangeFlag;
       public Object getAttrbiute(String attributeName) { 
          if (attributeName.equals("strangeflag")) return (Object)strangeFlag; 
          ...
       }
    }
    

    And then caller does:

       Boolean manipulableFlag = (Boolean) myOddClass.getAttrbiute ("strangeflag");
    

    And then later, if caller changes the value of manipulableFlag, you want that change to happen in the OddClass instance, just as though caller had instead used a setAttrbiute method.

    Is that what you're asking?

    In that case, you'd need a holder class, as suggested by Adam.

    0 讨论(0)
  • 2020-12-09 08:13

    If you are using Java 5 or higher then use AtomicBoolean

    0 讨论(0)
  • 2020-12-09 08:18

    Immutable classes are easier to work with. They'll never change and there will be no problems with concurrent code. (Basically, there are fewer possibilities to break them.)

    If you would like to return a reference to your Boolean value, you can use java.util.concurrent.atomic.AtomicBoolean if you're working with multiple threads or plain old org.apache.commons.lang.mutable.MutableBoolean.

    0 讨论(0)
提交回复
热议问题