How to get Boolean value from Object

后端 未结 4 713
盖世英雄少女心
盖世英雄少女心 2021-01-12 17:42

I tried different ways to fix this, but I am not able to fix it. I am trying to get the Boolean value of an Object passed inside this method of a checkBox:<

4条回答
  •  有刺的猬
    2021-01-12 18:15

    From the code you posted, and the result you are seeing, it doesn't look like newValue is a boolean. So you try to cast to a Boolean, but it's not one, so the error occurs.

    It's not clear what you're trying to do. Ideally you'd make newValue a boolean. If you can't do that, this should work:

    boolean newValue;
    if (newValue instanceof Boolean) { 
        changedValue = newValue; // autoboxing handles this for you
    } else if (newValue instanceof String) {
        changedValue = Boolean.parseBoolean(newValue);
    } else { 
        // handle other object types here, in a similar fashion to above
    }
    

    Note that this solution isn't really ideal, and is somewhat fragile. In some instances that is OK, but it is probably better to re-evaluate the inputs to your method to make them a little cleaner. If you can't, then the code above will work. It's really something only you can decide in the context of your solution.

提交回复
热议问题