I made this code:
protected Lala lala;
private Oyeha oyeha;
public void setLala(Lala lala) {
this.lala = lala;
}
this.oyeha = (Oyeha) this.lala;
executeHostBean = this.oyeha.updateMethod(a, b, c, d, e);
Lala is the parrent class.
Oyeha is the child which extends Lala.
But when i run this code, i got error:
java.lang.ClassCastException: $Proxy201
I can't find where my mistake is. Can somebody help me solve this problem, please? Thank you. :)
Your problem is probably that this.lala
is getting set to an instance of Lala which is not an instance of Oyeha. Since Oyeha is a subclass of Lala, it's possible to call public void setLala
with an argument that is an instance of Oyeha, like this:
Lala childInstance = new Oyeha();
setLala(childInstance);
but it's also possible to call that method with an argument that is just an instance of Lala, like this:
Lala parentInstance = new Lala();
setLala(parentInstance);
In the first case, this.lala
is an Oyeha, so you can cast it to Oyeha. But in the latter case, this.lala
is just a Lala, and your cast of this.lala
to Oyeha will fail, because a Lala is not an Oyeha.
If you have something like Spring injecting the Lala object, it could be creating a dynamic proxy object (that's what the error message suggests).
If downcasting is absolutely necessary in your design, you might want to rethink the design.
As an addition to the other answers (they've basically nailed it already):
Suppose you could downcast like that, such that the line this.oyeha = (Oyeha) this.lala
worked, and there was some field in Oyeha, say, test
.
If you then tried to use this.oyeha.test
somewhere, how would it know where test
is? Even worse, what if instances of Oyeha
take substantially more memory, and it arbitrarily picks an address outside what was put aside for the instance of Lala
?
I imagine that the inventors of Java foresaw a situation like that, and thus made it so that you cannot take an instance of a type and cast down to one of its subclasses.
(I would have put this in a comment, but there's too much)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.