How to get Boolean value from Object

久未见 提交于 2019-12-01 17:14:30

Instead of casting it, you can do something like

 Boolean.parseBoolean(string);

Here's some of the source code for the Boolean class in java.

// Boolean Constructor for String types.
public Boolean(String s) {
    this(toBoolean(s));
}
// parser.
public static boolean parseBoolean(String s) {
    return toBoolean(s);
}
// ...
// Here's the source for toBoolean.
// ...
private static boolean toBoolean(String name) { 
    return ((name != null) && name.equalsIgnoreCase("true"));
}

So as you can see, you need to pass a string with the value of "true" in order for the boolean value to be true. Otherwise it's false.

assert new Boolean( "ok" ) == false; 
assert new Boolean( "True" ) == true;
assert new Boolean( "false" ) == false;

assert Boolean.parseBoolean( "ok" ) == false; 
assert Boolean.parseBoolean( "True" ) == true;
assert Boolean.parseBoolean( "false" ) == false;

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.

If you know that your Preference is a CheckBoxPreference, then you can call isChecked(). It returns a boolean, not a Boolean, but that's probably close enough.

Here is some code from the APIDemos Device Administration sample (DeviceAdminSample.java).

private CheckBoxPreference mDisableCameraCheckbox;

public void onResume() {
    ...
    mDPM.setCameraDisabled(mDeviceAdminSample, mDisableCameraCheckbox.isChecked());
    ...
}

public boolean onPreferenceChange(Preference preference, Object newValue) {
...
    boolean value = (Boolean) newValue;
...
    else if (preference == mDisableCameraCheckbox) {
        mDPM.setCameraDisabled(mDeviceAdminSample, value);
        reloadSummaries();
    }
    return true;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!