我目前有一个项目,在那里我犯了一个错误,我无法弄清楚为什么它给了我这个错误。
我的结构:
Class: Variable (commands.lib.Variable);
Class: ImageLoader extends Variable (commands.lib.Variable);
然后我将一个变量转换为 ImageLoader:
// There is a variable made with: Variable v = new ImageLoader();
public static Variable(commands.lib.Variable) getVariable(String value){...}
ImageLoader t = (ImageLoader)getVariable(ab[2]);
但这给了我一个错误:
Exception in thread "main" java.lang.ClassCastException: commands.lib.Variable cannot be cast to commands.variable.ImageLoader
所以当然我用谷歌搜索了ClassCastException,这篇文章来自结果:Java 中“ClassCastException”的解释
这里有人解释:
Animal a = new Dog();
Dog d = (Dog) a; // no problem, the type animal can be casted to a dog, because its a dog
Cat c = (Dog) a; // raises class cast exception, you cant cast a dog to a cat
所以对于我的代码,它看起来像这样:
Variable a = new ImageLoader();
ImageLoader b = (ImageLoader) a; // This should work, but will throw a ClassCastException
Array c = (Array) a; // This should throw a error
所以我有点不知所措。我希望有人能帮助我,并修复错误。
问候,
罗宾