Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Boolean value from Object

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:

public boolean onPreferenceChange(Preference preference, Object newValue) 
{
    final String key = preference.getKey();
    referenceKey=key;
    Boolean changedValue=!(((Boolean)newValue).booleanValue()); //ClassCastException occurs here
}

I get:

java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean

like image 814
David Prun Avatar asked May 17 '12 20:05

David Prun


2 Answers

Instead of casting it, you can do something like

 Boolean.parseBoolean(string);
like image 62
OmniOwl Avatar answered Oct 06 '22 13:10

OmniOwl


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;
like image 43
Larry Battle Avatar answered Oct 06 '22 13:10

Larry Battle