重複の可能性:
オブジェクトからブール値を取得する方法
私はのBoolean
価値をObject
newValue
手に入れClassCastException
てここにたどり着こうとしています。しかし、私はそれを型キャストして、Boolean
なぜこれを取得するのexception
ですか?
Boolean changedValue=!((Boolean)newValue);
説明してもらえますか?ありがとうございました。
重複の可能性:
オブジェクトからブール値を取得する方法
私はのBoolean
価値をObject
newValue
手に入れClassCastException
てここにたどり着こうとしています。しかし、私はそれを型キャストして、Boolean
なぜこれを取得するのexception
ですか?
Boolean changedValue=!((Boolean)newValue);
説明してもらえますか?ありがとうございました。
A String
and a Boolean
are totally different classes, so you can't cast between them. You need to use Boolean.valueOf()
to get a Boolean
from the String.
.
It's not like C or C++ where you can forcibly cast anything to anything (though of course you can get into a lot of trouble doing so if you're not careful, since there's no guarantee an arbitrary cast will have any meaning).
And it's also not like C++ where if there are are type conversion operators defined, the cast will turn into an automatic call to one of the conversion operators. There are no automated conversions between object types in Java.
Java is a strongly typed language. If newValue
is not a Boolean
object then you will get a ClassCastException
if you try to cast it to a Boolean
. If newValue
is a String
representing a Boolean
value you can try the following code:
boolean changedValue = Boolean.parseBoolean( newValue )
Reference: http://docs.oracle.com/javase/6/docs/api/java/lang/Boolean.html#parseBoolean%28java.lang.String%29
If that is a string value, you'll want to use Boolean.valueOf(String)
method. Java does not convert objects into different types automatically only converts via autoboxing between wrappers and primitive types.