java.lang.ClassCastException

后端 未结 6 646
感情败类
感情败类 2020-11-29 07:27

Normally whats the reason to get java.lang.ClassCastException ..? I get the following error in my application

java.lang.ClassCastException: [Lcom.rsa.authag         


        
6条回答
  •  北海茫月
    2020-11-29 08:03

    A ClassCastException ocurrs when you try to cast an instance of an Object to a type that it is not. Casting only works when the casted object follows an "is a" relationship to the type you are trying to cast to. For Example

    Apple myApple = new Apple();
    Fruit myFruit = (Fruit)myApple;
    

    This works because an apple 'is a' fruit. However if we reverse this.

    Fruit myFruit = new Fruit();
    Apple myApple = (Apple)myFruit;
    

    This will throw a ClasCastException because a Fruit is not (always) an Apple.

    It is good practice to guard any explicit casts with an instanceof check first:

    if (myApple instanceof Fruit) {
      Fruit myFruit = (Fruit)myApple;
    }
    

提交回复
热议问题