2

重複の可能性:
オブジェクトからブール値を取得する方法

私はのBoolean価値をObject newValue手に入れClassCastExceptionてここにたどり着こうとしています。しかし、私はそれを型キャストして、Booleanなぜこれを取得するのexceptionですか?

Boolean changedValue=!((Boolean)newValue);

説明してもらえますか?ありがとうございました。

4

3 に答える 3

8

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.

于 2012-05-17T00:56:27.377 に答える
3

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

于 2012-05-17T00:56:59.517 に答える
1

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.

于 2012-05-17T00:56:47.567 に答える